TirsvadCLI Portfolio Library
Loading...
Searching...
No Matches
SignInManager.cs
1using Microsoft.IdentityModel.Tokens;
2
3using System.IdentityModel.Tokens.Jwt;
4using System.Security.Claims;
5using System.Text;
6
8
10
11public class SignInManager
12{
13 #region Fields
14
15 private readonly UserManager _userManager;
16 private readonly string _jwtKey;
17 private readonly string _jwtIssuer;
18 private readonly string _jwtAudience;
19
20 #endregion
21
22 #region Properties
23 // No properties defined
24 #endregion
25
26 #region Public Methods
27
28 public SignInManager(UserManager userManager, string jwtKey, string jwtIssuer, string jwtAudience)
29 {
30 _userManager = userManager;
31 _jwtKey = jwtKey;
32 _jwtIssuer = jwtIssuer;
33 _jwtAudience = jwtAudience;
34 }
35
36 public async Task<string?> AuthenticateAsync(string username, string password)
37 {
38 ApplicationUser? user = await _userManager.FindByNameAsync(username);
39 if (user == null)
40 return null;
41
42 bool valid = await UserManager.CheckPasswordAsync(user, password);
43 if (!valid)
44 return null;
45
46 // Generate JWT
47 JwtSecurityTokenHandler tokenHandler = new();
48 byte[] key = Encoding.UTF8.GetBytes(_jwtKey);
49 Claim[] claims =
50 [
51 new Claim(JwtRegisteredClaimNames.Sub, user.Id.ToString()),
52 new Claim(JwtRegisteredClaimNames.UniqueName, user.UserName ?? string.Empty),
53 new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
54 ];
55 SecurityTokenDescriptor tokenDescriptor = new()
56 {
57 Subject = new ClaimsIdentity(claims),
58 Expires = DateTime.UtcNow.AddHours(1),
59 Issuer = _jwtIssuer,
60 Audience = _jwtAudience,
61 SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
62 };
63 SecurityToken token = tokenHandler.CreateToken(tokenDescriptor);
64 return tokenHandler.WriteToken(token);
65 }
66
67 #endregion
68
69 #region Events
70 // No events defined
71 #endregion
72
73 #region CanDoXXX Commands
74 // No CanDoXXX commands defined
75 #endregion
76
77 #region OnXXX Commands
78 // No OnXXX commands defined
79 #endregion
80
81 #region Helpers
82 // No helpers defined
83 #endregion
84}
Provides user management operations for the application, including user retrieval,...
static Task< bool > CheckPasswordAsync(ApplicationUser user, string password)
Verifies a user's password against the stored password hash.
Represents an application user entity for authentication and authorization. Inherits from IdentityUse...
Guid Id
Gets or sets the unique identifier for the entity.
Definition IEntity.cs:14