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 roles) { var claims = new List { 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); } }