88 lines
2.7 KiB
C#
88 lines
2.7 KiB
C#
using System.IdentityModel.Tokens.Jwt;
|
|
using System.Security.Claims;
|
|
using Microsoft.Extensions.Logging;
|
|
using Microsoft.IdentityModel.Tokens;
|
|
|
|
namespace JWTService {
|
|
|
|
public interface IJWTService {
|
|
string CreateJwtToken();
|
|
JwtSecurityToken ReadJwtToken(string token);
|
|
}
|
|
public class JWTService : IJWTService {
|
|
|
|
private readonly ILogger<JWTService> _logger;
|
|
|
|
private readonly JwtSecurityTokenHandler _tokenHandler;
|
|
private readonly IJwtConfig _serviceConfig;
|
|
|
|
/// <summary>
|
|
///
|
|
/// </summary>
|
|
/// <param name="serviceConfig"></param>
|
|
public JWTService(
|
|
ILogger<JWTService> logger,
|
|
IJwtConfig serviceConfig
|
|
|
|
) {
|
|
_logger = logger;
|
|
_serviceConfig = serviceConfig;
|
|
_tokenHandler = new JwtSecurityTokenHandler();
|
|
}
|
|
|
|
public string? CreateJwtToken() {
|
|
if (_serviceConfig.Secret == null)
|
|
return null;
|
|
|
|
if (_serviceConfig.Expires == null)
|
|
return null;
|
|
|
|
|
|
var key = Convert.FromBase64String(_serviceConfig.Secret);
|
|
|
|
// add roles to claims identity from database
|
|
var claims = new List<Claim>() {};
|
|
|
|
|
|
var token = _tokenHandler.CreateToken(new SecurityTokenDescriptor {
|
|
IssuedAt = DateTime.UtcNow,
|
|
Subject = new ClaimsIdentity(claims),
|
|
Expires = DateTime.UtcNow.AddDays(_serviceConfig.Expires.Value),
|
|
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha512Signature),
|
|
});
|
|
|
|
return _tokenHandler.WriteToken(token);
|
|
}
|
|
|
|
|
|
//public string CreateJwtToken(IEnumerable<string> issuer, DateTime expires, string userId, string userEmail, string userName, IEnumerable<string> userRoles) {
|
|
// var key = Convert.FromBase64String(_serviceConfig.Secret);
|
|
|
|
// // add roles to claims identity from database
|
|
// var claims = new List<Claim>() {
|
|
// new Claim(ClaimTypes.Actor, userId),
|
|
// new Claim(ClaimTypes.Email, userEmail),
|
|
// new Claim(ClaimTypes.NameIdentifier, userName),
|
|
// // new Claim(ClaimTypes.Webpage, issuer)
|
|
// };
|
|
|
|
// foreach (var role in userRoles)
|
|
// claims.Add(new Claim(ClaimTypes.Role, role));
|
|
|
|
// foreach (var iss in issuer)
|
|
// claims.Add(new Claim(ClaimTypes.Webpage, iss));
|
|
|
|
// var token = _tokenHandler.CreateToken(new SecurityTokenDescriptor {
|
|
// IssuedAt = DateTime.UtcNow,
|
|
// Subject = new ClaimsIdentity(claims),
|
|
// Expires = expires,
|
|
// SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha512Signature),
|
|
// });
|
|
|
|
// return _tokenHandler.WriteToken(token);
|
|
//}
|
|
|
|
public JwtSecurityToken ReadJwtToken(string token) => _tokenHandler.ReadJwtToken(token);
|
|
}
|
|
}
|