From ff272ab1467af511a1975ee923c135199444fd0e Mon Sep 17 00:00:00 2001 From: James Tombleson Date: Sun, 6 Aug 2023 13:37:36 -0700 Subject: [PATCH] Added user role on creation. Updated Unixtime call. Updated how to add a role. Roles are now added to the claim --- Newsbot.Collector.Services/IdentityService.cs | 55 ++++++++++++++----- 1 file changed, 40 insertions(+), 15 deletions(-) diff --git a/Newsbot.Collector.Services/IdentityService.cs b/Newsbot.Collector.Services/IdentityService.cs index 3d587de..6df5bdc 100644 --- a/Newsbot.Collector.Services/IdentityService.cs +++ b/Newsbot.Collector.Services/IdentityService.cs @@ -3,6 +3,7 @@ using System.Security.Claims; using System.Text; using Microsoft.AspNetCore.Identity; using Microsoft.IdentityModel.Tokens; +using Newsbot.Collector.Api.Domain.Consts; using Newsbot.Collector.Domain.Results; using Newsbot.Collector.Domain.Entities; using Newsbot.Collector.Domain.Interfaces; @@ -16,22 +17,24 @@ public interface IIdentityService AuthenticationResult Register(string email, string password); AuthenticationResult Login(string email, string password); AuthenticationResult RefreshToken(string token, string refreshToken); - void AddRole(string roleName, string userId); + void AddRole(string name, string userId); } public class IdentityService : IIdentityService { private readonly UserManager _userManager; + private readonly RoleManager _roleManager; private readonly JwtSettings _jwtSettings; private readonly TokenValidationParameters _tokenValidationParameters; private readonly IRefreshTokenRepository _refreshTokenRepository; - public IdentityService(UserManager userManager, JwtSettings jwtSettings, TokenValidationParameters tokenValidationParameters, IRefreshTokenRepository refreshTokenRepository) + public IdentityService(UserManager userManager, JwtSettings jwtSettings, TokenValidationParameters tokenValidationParameters, IRefreshTokenRepository refreshTokenRepository, RoleManager roleManager) { _userManager = userManager; _jwtSettings = jwtSettings; _tokenValidationParameters = tokenValidationParameters; _refreshTokenRepository = refreshTokenRepository; + _roleManager = roleManager; } public AuthenticationResult Register(string email, string password) @@ -63,8 +66,11 @@ public class IdentityService : IIdentityService ErrorMessage = new List(createdUser.Result.Errors.Select(x => x.Description)) }; } - - return GenerateJwtToken(newUser); + + var addRole = _userManager.AddToRoleAsync(newUser, Authorization.UsersRole); + addRole.Wait(); + + return GenerateJwtToken(newUser); } public AuthenticationResult Login(string email, string password) @@ -109,8 +115,9 @@ public class IdentityService : IIdentityService var expiryDateUnix = long.Parse(validatedToken.Claims.Single(x => x.Type == JwtRegisteredClaimNames.Exp).Value); // generate the unix epoc, add expiry time - var expiryDateTimeUtc = new DateTime(1970, 0, 0, 0, 0, 0, DateTimeKind.Utc) - .AddSeconds(expiryDateUnix); + + var unixTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); + var expiryDateTimeUtc = unixTime.AddSeconds(expiryDateUnix); // if it expires in the future if (expiryDateTimeUtc > DateTime.Now) @@ -179,7 +186,7 @@ public class IdentityService : IIdentityService return GenerateJwtToken(user.Result); } - public void AddRole(string roleName, string userId) + public void AddRole(string name, string userId) { var user = _userManager.FindByIdAsync(userId); user.Wait(); @@ -189,7 +196,14 @@ public class IdentityService : IIdentityService throw new Exception("User was not found"); } - _userManager.AddToRoleAsync(user.Result, roleName); + if (!name.Equals(Authorization.AdministratorClaim) + || !name.Equals(Authorization.UserClaim)) + { + throw new Exception("Invalid role"); + } + + var addRole = _userManager.AddToRoleAsync(user.Result, name); + addRole.Wait(); } private ClaimsPrincipal? CheckTokenSigner(string token) @@ -221,15 +235,25 @@ public class IdentityService : IIdentityService { var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes(_jwtSettings.Secret ?? ""); + + var claims = new List + { + new Claim(JwtRegisteredClaimNames.Sub, user.Email ?? ""), + new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), + new Claim(JwtRegisteredClaimNames.Email, user.Email ?? ""), + new Claim("id", user.Id) + }; + + var userRoles = _userManager.GetRolesAsync(user); + userRoles.Wait(); + foreach (var role in userRoles.Result) + { + claims.Add(new Claim(ClaimTypes.Role, role)); + } + var tokenDescriptor = new SecurityTokenDescriptor { - Subject = new ClaimsIdentity(new[] - { - new Claim(JwtRegisteredClaimNames.Sub, user.Email ?? ""), - new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), - new Claim(JwtRegisteredClaimNames.Email, user.Email ?? ""), - new Claim("id", user.Id) - }), + Subject = new ClaimsIdentity(claims), Expires = DateTime.UtcNow.AddHours(3), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) @@ -239,6 +263,7 @@ public class IdentityService : IIdentityService var refreshToken = new RefreshTokenEntity { + Token = token.Id, JwtId = token.Id, UserId = user.Id, CreatedDate = DateTime.UtcNow,