From 918b685ad99a5abd430c9f9ae5a18bd296a32df9 Mon Sep 17 00:00:00 2001 From: 杨宇千 Date: Sun, 21 Jul 2019 23:28:21 +0800 Subject: WIP: change auth handler. --- Timeline/Authenticate/AuthHandler.cs | 29 ++++++++++++++++------------- Timeline/Startup.cs | 13 +------------ 2 files changed, 17 insertions(+), 25 deletions(-) diff --git a/Timeline/Authenticate/AuthHandler.cs b/Timeline/Authenticate/AuthHandler.cs index 63442481..80bbaf14 100644 --- a/Timeline/Authenticate/AuthHandler.cs +++ b/Timeline/Authenticate/AuthHandler.cs @@ -1,12 +1,13 @@ using Microsoft.AspNetCore.Authentication; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; -using Microsoft.IdentityModel.Tokens; using Microsoft.Net.Http.Headers; using System; -using System.IdentityModel.Tokens.Jwt; +using System.Linq; +using System.Security.Claims; using System.Text.Encodings.Web; using System.Threading.Tasks; +using Timeline.Services; namespace Timeline.Authenticate { @@ -22,18 +23,18 @@ namespace Timeline.Authenticate /// The query param key to search for token. If null then query params are not searched for token. Default to "token". /// public string TokenQueryParamKey { get; set; } = "token"; - - public TokenValidationParameters TokenValidationParameters { get; set; } = new TokenValidationParameters(); } class AuthHandler : AuthenticationHandler { private readonly ILogger _logger; + private readonly IUserService _userService; - public AuthHandler(IOptionsMonitor options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock) + public AuthHandler(IOptionsMonitor options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock, IUserService userService) : base(options, logger, encoder, clock) { _logger = logger.CreateLogger(); + _userService = userService; } // return null if no token is found @@ -73,22 +74,24 @@ namespace Timeline.Authenticate return AuthenticateResult.NoResult(); } - var handler = new JwtSecurityTokenHandler(); try { - var principal = handler.ValidateToken(token, Options.TokenValidationParameters, out var validatedToken); + var userInfo = await _userService.VerifyToken(token); + + var identity = new ClaimsIdentity(); + identity.AddClaim(new Claim(identity.NameClaimType, userInfo.Username, ClaimValueTypes.String)); + identity.AddClaims(Entities.UserUtility.IsAdminToRoleArray(userInfo.IsAdmin).Select(role => new Claim(identity.RoleClaimType, role, ClaimValueTypes.String))); + + var principal = new ClaimsPrincipal(); + principal.AddIdentity(identity); + return AuthenticateResult.Success(new AuthenticationTicket(principal, AuthConstants.Scheme)); } - catch (SecurityTokenException e) + catch (Exception e) { _logger.LogInformation(e, "A jwt token validation failed."); return AuthenticateResult.Fail(e); } - catch (Exception e) - { - _logger.LogError(e, "Arguments passed to the JwtSecurityTokenHandler.ValidateToken are bad."); - throw e; - } } } } diff --git a/Timeline/Startup.cs b/Timeline/Startup.cs index 83170c43..374b918a 100644 --- a/Timeline/Startup.cs +++ b/Timeline/Startup.cs @@ -7,8 +7,6 @@ using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; -using Microsoft.IdentityModel.Tokens; -using System.Text; using Timeline.Authenticate; using Timeline.Configs; using Timeline.Formatters; @@ -53,16 +51,7 @@ namespace Timeline var jwtConfig = Configuration.GetSection(nameof(JwtConfig)).Get(); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) - .AddScheme(AuthConstants.Scheme, AuthConstants.DisplayName, o => - { - o.TokenValidationParameters.ValidateIssuer = true; - o.TokenValidationParameters.ValidateAudience = true; - o.TokenValidationParameters.ValidateIssuerSigningKey = true; - o.TokenValidationParameters.ValidateLifetime = true; - o.TokenValidationParameters.ValidIssuer = jwtConfig.Issuer; - o.TokenValidationParameters.ValidAudience = jwtConfig.Audience; - o.TokenValidationParameters.IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtConfig.SigningKey)); - }); + .AddScheme(AuthConstants.Scheme, AuthConstants.DisplayName, o => { }); services.AddScoped(); services.AddScoped(); -- cgit v1.2.3