|
|
|
@ -1,8 +1,11 @@
|
|
|
|
|
using System.Security.Claims;
|
|
|
|
|
using System.Globalization;
|
|
|
|
|
using System.IdentityModel.Tokens.Jwt;
|
|
|
|
|
using System.Security.Claims;
|
|
|
|
|
using Infrastructure.Utils;
|
|
|
|
|
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
|
|
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
|
|
|
using Microsoft.IdentityModel.JsonWebTokens;
|
|
|
|
|
using Microsoft.IdentityModel.Tokens;
|
|
|
|
|
using JwtRegisteredClaimNames = Microsoft.IdentityModel.JsonWebTokens.JwtRegisteredClaimNames;
|
|
|
|
|
|
|
|
|
|
namespace Infrastructure.Security;
|
|
|
|
|
|
|
|
|
@ -11,9 +14,15 @@ public interface ITokenBuilder
|
|
|
|
|
IList<Claim> GetClaimsByUserContext(IUserContext userContext);
|
|
|
|
|
|
|
|
|
|
void SetUserContext(TokenValidatedContext context);
|
|
|
|
|
|
|
|
|
|
TokenInfo GenerateJwtTokenInfo(IReadOnlyCollection<Claim> claims);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public class TokenBuilder : ITokenBuilder
|
|
|
|
|
public class TokenBuilder(
|
|
|
|
|
PermissionOptions permissionOptions,
|
|
|
|
|
JwtSecurityTokenHandler jwtSecurityTokenHandler,
|
|
|
|
|
IEncryptionService encryptionService)
|
|
|
|
|
: ITokenBuilder
|
|
|
|
|
{
|
|
|
|
|
public IList<Claim> GetClaimsByUserContext(IUserContext userContext)
|
|
|
|
|
{
|
|
|
|
@ -23,6 +32,10 @@ public class TokenBuilder : ITokenBuilder
|
|
|
|
|
new(JwtRegisteredClaimNames.NameId, userContext.Id.ToString()),
|
|
|
|
|
new(JwtRegisteredClaimNames.Name, userContext.Name),
|
|
|
|
|
new(JwtRegisteredClaimNames.Email, userContext.Email),
|
|
|
|
|
new(JwtRegisteredClaimNames.Iat,
|
|
|
|
|
EpochTime.GetIntDate(DateTime.Now).ToString(CultureInfo.InvariantCulture),
|
|
|
|
|
ClaimValueTypes.Integer64),
|
|
|
|
|
new(JwtRegisteredClaimNames.Exp, permissionOptions.Expiration.ToString())
|
|
|
|
|
};
|
|
|
|
|
claims.AddRange(userContext.RoleIds.Select(rId => new Claim(ClaimTypes.Role, rId)));
|
|
|
|
|
return claims;
|
|
|
|
@ -42,4 +55,18 @@ public class TokenBuilder : ITokenBuilder
|
|
|
|
|
userContext.RoleIds = principal.Claims.Where(c => c.Type == ClaimTypes.Role).Select(c => c.Value).ToArray();
|
|
|
|
|
userContext.RemoteIpAddress = context.HttpContext.GetRequestIp();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public TokenInfo GenerateJwtTokenInfo(IReadOnlyCollection<Claim> claims)
|
|
|
|
|
{
|
|
|
|
|
var jwtToken = new JwtSecurityToken(
|
|
|
|
|
issuer: permissionOptions.Issuer,
|
|
|
|
|
audience: permissionOptions.Audience,
|
|
|
|
|
claims: claims,
|
|
|
|
|
notBefore: DateTime.Now,
|
|
|
|
|
expires: DateTime.Now.AddSeconds(permissionOptions.Expiration),
|
|
|
|
|
signingCredentials: permissionOptions.SigningCredentials);
|
|
|
|
|
var token = jwtSecurityTokenHandler.WriteToken(jwtToken);
|
|
|
|
|
return new TokenInfo(encryptionService.Encrypt(token), permissionOptions.Expiration,
|
|
|
|
|
JwtBearerDefaults.AuthenticationScheme);
|
|
|
|
|
}
|
|
|
|
|
}
|