diff options
Diffstat (limited to 'Timeline/Authentication')
-rw-r--r-- | Timeline/Authentication/Attribute.cs | 21 | ||||
-rw-r--r-- | Timeline/Authentication/AuthHandler.cs | 98 | ||||
-rw-r--r-- | Timeline/Authentication/PrincipalExtensions.cs | 13 |
3 files changed, 132 insertions, 0 deletions
diff --git a/Timeline/Authentication/Attribute.cs b/Timeline/Authentication/Attribute.cs new file mode 100644 index 00000000..370b37e1 --- /dev/null +++ b/Timeline/Authentication/Attribute.cs @@ -0,0 +1,21 @@ +using Microsoft.AspNetCore.Authorization;
+using Timeline.Entities;
+
+namespace Timeline.Authentication
+{
+ public class AdminAuthorizeAttribute : AuthorizeAttribute
+ {
+ public AdminAuthorizeAttribute()
+ {
+ Roles = UserRoles.Admin;
+ }
+ }
+
+ public class UserAuthorizeAttribute : AuthorizeAttribute
+ {
+ public UserAuthorizeAttribute()
+ {
+ Roles = UserRoles.User;
+ }
+ }
+}
diff --git a/Timeline/Authentication/AuthHandler.cs b/Timeline/Authentication/AuthHandler.cs new file mode 100644 index 00000000..47ed1d71 --- /dev/null +++ b/Timeline/Authentication/AuthHandler.cs @@ -0,0 +1,98 @@ +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;
+
+namespace Timeline.Authentication
+{
+ static class AuthConstants
+ {
+ public const string Scheme = "Bearer";
+ public const string DisplayName = "My Jwt Auth Scheme";
+ }
+
+ public class AuthOptions : 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 AuthHandler : AuthenticationHandler<AuthOptions>
+ {
+ private readonly ILogger<AuthHandler> _logger;
+ private readonly IUserService _userService;
+
+ public AuthHandler(IOptionsMonitor<AuthOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock, IUserService userService)
+ : base(options, logger, encoder, clock)
+ {
+ _logger = logger.CreateLogger<AuthHandler>();
+ _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(Resources.Authentication.AuthHandler.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(Resources.Authentication.AuthHandler.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(Resources.Authentication.AuthHandler.LogTokenNotFound);
+ return AuthenticateResult.NoResult();
+ }
+
+ try
+ {
+ var userInfo = await _userService.VerifyToken(token);
+
+ var identity = new ClaimsIdentity(AuthConstants.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, AuthConstants.Scheme));
+ }
+ catch (Exception e) when (e! is ArgumentException)
+ {
+ _logger.LogInformation(e, Resources.Authentication.AuthHandler.LogTokenValidationFail);
+ return AuthenticateResult.Fail(e);
+ }
+ }
+ }
+}
diff --git a/Timeline/Authentication/PrincipalExtensions.cs b/Timeline/Authentication/PrincipalExtensions.cs new file mode 100644 index 00000000..8d77ab62 --- /dev/null +++ b/Timeline/Authentication/PrincipalExtensions.cs @@ -0,0 +1,13 @@ +using System.Security.Principal;
+using Timeline.Entities;
+
+namespace Timeline.Authentication
+{
+ internal static class PrincipalExtensions
+ {
+ internal static bool IsAdministrator(this IPrincipal principal)
+ {
+ return principal.IsInRole(UserRoles.Admin);
+ }
+ }
+}
|