1
|
using System.IdentityModel.Tokens.Jwt;
|
2
|
using System.Security.Claims;
|
3
|
using System.Text;
|
4
|
using Core.Entities;
|
5
|
using Microsoft.Extensions.Configuration;
|
6
|
using Microsoft.Extensions.Options;
|
7
|
using Microsoft.IdentityModel.Tokens;
|
8
|
|
9
|
namespace Core.Authentication;
|
10
|
|
11
|
public interface IJwtUtils
|
12
|
{
|
13
|
public string GenerateJwtToken(User user, DateTime? expiration = null);
|
14
|
public Guid? ValidateJwtToken(string token);
|
15
|
}
|
16
|
|
17
|
public class JwtUtils : IJwtUtils
|
18
|
{
|
19
|
private const int EXPIRATION_SECONDS = 8 * 60 * 60; // 8 hrs
|
20
|
|
21
|
private readonly JwtConfig _jwtConfig;
|
22
|
private readonly TokenValidationParameters _tokenValidationParameters;
|
23
|
|
24
|
public JwtUtils(IOptions<JwtConfig> jwtConfig, TokenValidationParameters tokenValidationParameters)
|
25
|
{
|
26
|
_jwtConfig = jwtConfig.Value;
|
27
|
_tokenValidationParameters = tokenValidationParameters;
|
28
|
}
|
29
|
|
30
|
public static TokenValidationParameters GetTokenValidationParameters(ConfigurationManager configuration)
|
31
|
{
|
32
|
return new TokenValidationParameters
|
33
|
{
|
34
|
RequireExpirationTime = true,
|
35
|
ValidateIssuerSigningKey = false,
|
36
|
IssuerSigningKey =
|
37
|
new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["JwtConfig:Secret"])),
|
38
|
ValidateIssuer = false,
|
39
|
ValidIssuer = configuration["JwtConfig:Issuer"],
|
40
|
ValidateAudience = false,
|
41
|
ValidateLifetime = true
|
42
|
};
|
43
|
}
|
44
|
|
45
|
|
46
|
public string GenerateJwtToken(User user, DateTime? expiration = null)
|
47
|
{
|
48
|
expiration ??= DateTime.Now.AddHours(10);
|
49
|
|
50
|
var tokenHandler = new JwtSecurityTokenHandler();
|
51
|
var key = Encoding.ASCII.GetBytes(_jwtConfig.Secret);
|
52
|
var tokenDescriptor = new SecurityTokenDescriptor
|
53
|
{
|
54
|
Subject = new ClaimsIdentity(new[] {new Claim("id", user.Id.ToString())}),
|
55
|
Expires = expiration,
|
56
|
SigningCredentials =
|
57
|
new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
|
58
|
};
|
59
|
var token = tokenHandler.CreateToken(tokenDescriptor);
|
60
|
return tokenHandler.WriteToken(token);
|
61
|
}
|
62
|
|
63
|
public Guid? ValidateJwtToken(string? token)
|
64
|
{
|
65
|
if (token == null)
|
66
|
return null;
|
67
|
|
68
|
var tokenHandler = new JwtSecurityTokenHandler();
|
69
|
var key = Encoding.ASCII.GetBytes(_jwtConfig.Secret);
|
70
|
try
|
71
|
{
|
72
|
tokenHandler.ValidateToken(token, _tokenValidationParameters, out SecurityToken validatedToken);
|
73
|
|
74
|
var jwtToken = (JwtSecurityToken) validatedToken;
|
75
|
var userId = Guid.Parse(jwtToken.Claims.First(x => x.Type == "id").Value);
|
76
|
|
77
|
// return user id from JWT token if validation successful
|
78
|
return userId;
|
79
|
}
|
80
|
catch
|
81
|
{
|
82
|
// return null if validation fails
|
83
|
return null;
|
84
|
}
|
85
|
}
|
86
|
}
|