forked from ddrilling/AsbCloudServer
50 lines
1.5 KiB
C#
50 lines
1.5 KiB
C#
using System.IdentityModel.Tokens.Jwt;
|
|
using System.Security.Claims;
|
|
using System.Text;
|
|
using AsbCloudDb.Model;
|
|
using Microsoft.IdentityModel.Tokens;
|
|
|
|
namespace AsbCloudWebApi.IntegrationTests;
|
|
|
|
public static class ApiTokenHelper
|
|
{
|
|
public static string GetAdminUserToken()
|
|
{
|
|
var user = new User()
|
|
{
|
|
Id = 1,
|
|
IdCompany = 1,
|
|
Login = "test_user"
|
|
};
|
|
var roles = new[] { "root" };
|
|
|
|
return CreateToken(user, roles);
|
|
}
|
|
|
|
private static string CreateToken(User user, IEnumerable<string> roles)
|
|
{
|
|
var claims = new List<Claim>
|
|
{
|
|
new("id", user.Id.ToString()),
|
|
new(ClaimsIdentity.DefaultNameClaimType, user.Login),
|
|
new("idCompany", user.IdCompany.ToString()),
|
|
};
|
|
|
|
claims.AddRange(roles.Select(role => new Claim(ClaimTypes.Role, role)));
|
|
|
|
const string secret = "супер секретный ключ для шифрования";
|
|
|
|
var key = Encoding.ASCII.GetBytes(secret);
|
|
var tokenDescriptor = new SecurityTokenDescriptor
|
|
{
|
|
Issuer = "a",
|
|
Audience = "a",
|
|
Subject = new ClaimsIdentity(claims),
|
|
Expires = DateTime.UtcNow.AddHours(1),
|
|
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
|
|
};
|
|
var tokenHandler = new JwtSecurityTokenHandler();
|
|
var token = tokenHandler.CreateToken(tokenDescriptor);
|
|
return tokenHandler.WriteToken(token);
|
|
}
|
|
} |