-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
TokenService.cs
199 lines (179 loc) · 8.44 KB
/
TokenService.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
using DN.WebApi.Application.Abstractions.Services.General;
using DN.WebApi.Application.Abstractions.Services.Identity;
using DN.WebApi.Application.Exceptions;
using DN.WebApi.Application.Settings;
using DN.WebApi.Application.Wrapper;
using DN.WebApi.Domain.Constants;
using DN.WebApi.Infrastructure.Identity.Models;
using DN.WebApi.Infrastructure.Persistence;
using DN.WebApi.Shared.DTOs.Identity.Requests;
using DN.WebApi.Shared.DTOs.Identity.Responses;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Net;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace DN.WebApi.Infrastructure.Identity.Services
{
public class TokenService : ITokenService
{
private readonly TenantManagementDbContext _tenantContext;
private readonly UserManager<ApplicationUser> _userManager;
private readonly RoleManager<ApplicationRole> _roleManager;
private readonly IStringLocalizer<TokenService> _localizer;
private readonly MailSettings _mailSettings;
private readonly JwtSettings _config;
private readonly ITenantService _tenantService;
public TokenService(
UserManager<ApplicationUser> userManager,
RoleManager<ApplicationRole> roleManager,
IOptions<JwtSettings> config,
IStringLocalizer<TokenService> localizer,
IOptions<MailSettings> mailSettings,
ITenantService tenantService,
TenantManagementDbContext tenantContext)
{
_userManager = userManager;
_roleManager = roleManager;
_localizer = localizer;
_mailSettings = mailSettings.Value;
_config = config.Value;
_tenantService = tenantService;
_tenantContext = tenantContext;
}
public async Task<IResult<TokenResponse>> GetTokenAsync(TokenRequest request, string ipAddress)
{
var user = await _userManager.FindByEmailAsync(request.Email.Trim());
if (user == null)
{
throw new IdentityException(_localizer["identity.usernotfound"], statusCode: HttpStatusCode.Unauthorized);
}
string tenantKey = user.TenantKey;
var tenant = await _tenantContext.Tenants.Where(a => a.Key == tenantKey).FirstOrDefaultAsync();
if (tenantKey != MultitenancyConstants.Root.Key)
{
if (!tenant.IsActive)
{
throw new InvalidTenantException(_localizer["tenant.inactive"]);
}
if (DateTime.UtcNow > tenant.ValidUpto)
{
throw new InvalidTenantException(_localizer["tenant.expired"]);
}
}
if (!user.IsActive)
{
throw new IdentityException(_localizer["identity.usernotactive"], statusCode: HttpStatusCode.Unauthorized);
}
if (_mailSettings.EnableVerification && !user.EmailConfirmed)
{
throw new IdentityException(_localizer["identity.emailnotconfirmed"], statusCode: HttpStatusCode.Unauthorized);
}
bool passwordValid = await _userManager.CheckPasswordAsync(user, request.Password);
if (!passwordValid)
{
throw new IdentityException(_localizer["identity.invalidcredentials"], statusCode: HttpStatusCode.Unauthorized);
}
user.RefreshToken = GenerateRefreshToken();
user.RefreshTokenExpiryTime = DateTime.UtcNow.AddDays(_config.RefreshTokenExpirationInDays);
await _userManager.UpdateAsync(user);
string token = GenerateJwtAsync(user, ipAddress);
var response = new TokenResponse(token, user.RefreshToken, user.RefreshTokenExpiryTime);
return await Result<TokenResponse>.SuccessAsync(response);
}
public async Task<IResult<TokenResponse>> RefreshTokenAsync(RefreshTokenRequest request, string ipAddress)
{
if (request is null)
{
throw new IdentityException(_localizer["identity.invalidtoken"], statusCode: HttpStatusCode.Unauthorized);
}
var userPrincipal = GetPrincipalFromExpiredToken(request.Token);
string userEmail = userPrincipal.FindFirstValue(ClaimTypes.Email);
var user = await _userManager.FindByEmailAsync(userEmail);
if (user == null)
{
throw new IdentityException(_localizer["identity.usernotfound"], statusCode: HttpStatusCode.NotFound);
}
if (user.RefreshToken != request.RefreshToken || user.RefreshTokenExpiryTime <= DateTime.UtcNow)
{
throw new IdentityException(_localizer["identity.invalidtoken"], statusCode: HttpStatusCode.Unauthorized);
}
string token = GenerateEncryptedToken(GetSigningCredentials(), GetClaimsAsync(user, ipAddress));
user.RefreshToken = GenerateRefreshToken();
user.RefreshTokenExpiryTime = DateTime.UtcNow.AddDays(_config.RefreshTokenExpirationInDays);
await _userManager.UpdateAsync(user);
var response = new TokenResponse(token, user.RefreshToken, user.RefreshTokenExpiryTime);
return await Result<TokenResponse>.SuccessAsync(response);
}
private string GenerateJwtAsync(ApplicationUser user, string ipAddress)
{
return GenerateEncryptedToken(GetSigningCredentials(), GetClaimsAsync(user, ipAddress));
}
private IEnumerable<Claim> GetClaimsAsync(ApplicationUser user, string ipAddress)
{
string tenantKey = _tenantService.GetCurrentTenant()?.Key;
return new List<Claim>
{
new(ClaimTypes.NameIdentifier, user.Id),
new(ClaimTypes.Email, user.Email),
new("fullName", $"{user.FirstName} {user.LastName}"),
new(ClaimTypes.Name, user.FirstName),
new(ClaimTypes.Surname, user.LastName),
new("ipAddress", ipAddress),
new("tenantKey", tenantKey)
};
}
private string GenerateRefreshToken()
{
byte[] randomNumber = new byte[32];
using var rng = RandomNumberGenerator.Create();
rng.GetBytes(randomNumber);
return Convert.ToBase64String(randomNumber);
}
private string GenerateEncryptedToken(SigningCredentials signingCredentials, IEnumerable<Claim> claims)
{
var token = new JwtSecurityToken(
claims: claims,
expires: DateTime.UtcNow.AddMinutes(_config.TokenExpirationInMinutes),
signingCredentials: signingCredentials);
var tokenHandler = new JwtSecurityTokenHandler();
return tokenHandler.WriteToken(token);
}
private ClaimsPrincipal GetPrincipalFromExpiredToken(string token)
{
var tokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config.Key)),
ValidateIssuer = false,
ValidateAudience = false,
RoleClaimType = ClaimTypes.Role,
ClockSkew = TimeSpan.Zero
};
var tokenHandler = new JwtSecurityTokenHandler();
var principal = tokenHandler.ValidateToken(token, tokenValidationParameters, out var securityToken);
if (securityToken is not JwtSecurityToken jwtSecurityToken ||
!jwtSecurityToken.Header.Alg.Equals(
SecurityAlgorithms.HmacSha256,
StringComparison.InvariantCultureIgnoreCase))
{
throw new IdentityException(_localizer["identity.invalidtoken"], statusCode: HttpStatusCode.Unauthorized);
}
return principal;
}
private SigningCredentials GetSigningCredentials()
{
byte[] secret = Encoding.UTF8.GetBytes(_config.Key);
return new SigningCredentials(new SymmetricSecurityKey(secret), SecurityAlgorithms.HmacSha256);
}
}
}