From e347b4a4092a24ff7106ffd3aca67d6ca7decca8 Mon Sep 17 00:00:00 2001 From: crupest Date: Sun, 21 Apr 2019 23:23:49 +0800 Subject: Allow ordinary user to patch his password. --- Timeline/Services/JwtService.cs | 22 +++++++++++++--------- 1 file changed, 13 insertions(+), 9 deletions(-) (limited to 'Timeline/Services/JwtService.cs') diff --git a/Timeline/Services/JwtService.cs b/Timeline/Services/JwtService.cs index 91e7f879..bf470354 100644 --- a/Timeline/Services/JwtService.cs +++ b/Timeline/Services/JwtService.cs @@ -7,25 +7,28 @@ using System.Linq; using System.Security.Claims; using System.Text; using Timeline.Configs; +using Timeline.Entities; namespace Timeline.Services { public interface IJwtService { /// - /// Create a JWT token for a given user id. + /// Create a JWT token for a given user info. /// - /// The user id used to generate token. + /// The user id contained in generate token. + /// The username contained in token. + /// The roles contained in token. /// Return the generated token. - string GenerateJwtToken(long userId, string[] roles); + string GenerateJwtToken(long userId, string username, string[] roles); /// /// Verify a JWT token. /// Return null is is null. /// /// The token string to verify. - /// Return null if is null or token is invalid. Return the saved user id otherwise. - long? VerifyJwtToken(string token); + /// Return null if is null or token is invalid. Return the saved user info otherwise. + UserInfo VerifyJwtToken(string token); } @@ -41,12 +44,13 @@ namespace Timeline.Services _logger = logger; } - public string GenerateJwtToken(long id, string[] roles) + public string GenerateJwtToken(long id, string username, string[] roles) { var jwtConfig = _jwtConfig.CurrentValue; var identity = new ClaimsIdentity(); identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, id.ToString())); + identity.AddClaim(new Claim(identity.NameClaimType, username)); identity.AddClaims(roles.Select(role => new Claim(identity.RoleClaimType, role))); var tokenDescriptor = new SecurityTokenDescriptor() @@ -67,13 +71,12 @@ namespace Timeline.Services } - public long? VerifyJwtToken(string token) + public UserInfo VerifyJwtToken(string token) { if (token == null) return null; var config = _jwtConfig.CurrentValue; - try { var principal = _tokenHandler.ValidateToken(token, new TokenValidationParameters @@ -87,7 +90,8 @@ namespace Timeline.Services IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(config.SigningKey)) }, out SecurityToken validatedToken); - return long.Parse(principal.FindAll(ClaimTypes.NameIdentifier).Single().Value); + return new UserInfo(principal.Identity.Name, + principal.FindAll(ClaimTypes.Role).Select(c => c.Value).ToArray()); } catch (Exception e) { -- cgit v1.2.3