aboutsummaryrefslogtreecommitdiff
path: root/Timeline/Auth/MyAuthenticationHandler.cs
diff options
context:
space:
mode:
author杨宇千 <crupest@outlook.com>2019-10-31 15:02:03 +0800
committerGitHub <noreply@github.com>2019-10-31 15:02:03 +0800
commit37a2e6340ab20de1f9e847d795c0cbec9846de97 (patch)
treeba42530cf4f13621a7a3a7ff661e383117119883 /Timeline/Auth/MyAuthenticationHandler.cs
parenta175f8328d7a6c36464676d54fc50d03e64be0af (diff)
parent2c3744ab5db476b64a32c19b50153e3e6166b0e6 (diff)
downloadtimeline-37a2e6340ab20de1f9e847d795c0cbec9846de97.tar.gz
timeline-37a2e6340ab20de1f9e847d795c0cbec9846de97.tar.bz2
timeline-37a2e6340ab20de1f9e847d795c0cbec9846de97.zip
Merge pull request #53 from crupest/nickname
Add nickname support.
Diffstat (limited to 'Timeline/Auth/MyAuthenticationHandler.cs')
-rw-r--r--Timeline/Auth/MyAuthenticationHandler.cs99
1 files changed, 99 insertions, 0 deletions
diff --git a/Timeline/Auth/MyAuthenticationHandler.cs b/Timeline/Auth/MyAuthenticationHandler.cs
new file mode 100644
index 00000000..f5dcd697
--- /dev/null
+++ b/Timeline/Auth/MyAuthenticationHandler.cs
@@ -0,0 +1,99 @@
+using Microsoft.AspNetCore.Authentication;
+using Microsoft.Extensions.Logging;
+using Microsoft.Extensions.Options;
+using Microsoft.Net.Http.Headers;
+using System;
+using System.Linq;
+using System.Security.Claims;
+using System.Text.Encodings.Web;
+using System.Threading.Tasks;
+using Timeline.Models;
+using Timeline.Services;
+using static Timeline.Resources.Authentication.AuthHandler;
+
+namespace Timeline.Auth
+{
+ public static class AuthenticationConstants
+ {
+ public const string Scheme = "Bearer";
+ public const string DisplayName = "My Jwt Auth Scheme";
+ }
+
+ public class MyAuthenticationOptions : AuthenticationSchemeOptions
+ {
+ /// <summary>
+ /// The query param key to search for token. If null then query params are not searched for token. Default to <c>"token"</c>.
+ /// </summary>
+ public string TokenQueryParamKey { get; set; } = "token";
+ }
+
+ public class MyAuthenticationHandler : AuthenticationHandler<MyAuthenticationOptions>
+ {
+ private readonly ILogger<MyAuthenticationHandler> _logger;
+ private readonly IUserService _userService;
+
+ public MyAuthenticationHandler(IOptionsMonitor<MyAuthenticationOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock, IUserService userService)
+ : base(options, logger, encoder, clock)
+ {
+ _logger = logger.CreateLogger<MyAuthenticationHandler>();
+ _userService = userService;
+ }
+
+ // return null if no token is found
+ private string? ExtractToken()
+ {
+ // check the authorization header
+ string header = Request.Headers[HeaderNames.Authorization];
+ if (!string.IsNullOrEmpty(header) && header.StartsWith("Bearer ", StringComparison.InvariantCultureIgnoreCase))
+ {
+ var token = header.Substring("Bearer ".Length).Trim();
+ _logger.LogInformation(LogTokenFoundInHeader, token);
+ return token;
+ }
+
+ // check the query params
+ var paramQueryKey = Options.TokenQueryParamKey;
+ if (!string.IsNullOrEmpty(paramQueryKey))
+ {
+ string token = Request.Query[paramQueryKey];
+ if (!string.IsNullOrEmpty(token))
+ {
+ _logger.LogInformation(LogTokenFoundInQuery, paramQueryKey, token);
+ return token;
+ }
+ }
+
+ // not found anywhere then return null
+ return null;
+ }
+
+ protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
+ {
+ var token = ExtractToken();
+ if (string.IsNullOrEmpty(token))
+ {
+ _logger.LogInformation(LogTokenNotFound);
+ return AuthenticateResult.NoResult();
+ }
+
+ try
+ {
+ var userInfo = await _userService.VerifyToken(token);
+
+ var identity = new ClaimsIdentity(AuthenticationConstants.Scheme);
+ identity.AddClaim(new Claim(identity.NameClaimType, userInfo.Username, ClaimValueTypes.String));
+ identity.AddClaims(UserRoleConvert.ToArray(userInfo.Administrator).Select(role => new Claim(identity.RoleClaimType, role, ClaimValueTypes.String)));
+
+ var principal = new ClaimsPrincipal();
+ principal.AddIdentity(identity);
+
+ return AuthenticateResult.Success(new AuthenticationTicket(principal, AuthenticationConstants.Scheme));
+ }
+ catch (Exception e) when (!(e is ArgumentException))
+ {
+ _logger.LogInformation(e, LogTokenValidationFail);
+ return AuthenticateResult.Fail(e);
+ }
+ }
+ }
+}