using IdentityServer.PublishedLanguage.Dto; using IdentityServer.Wrapper.Services; using Microsoft.AspNetCore.Authentication; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using NDB.Security.Authentication.Identity.Abstractions; using System.Net.Http.Headers; using System.Security.Claims; using System.Text.Encodings.Web; using System.Threading.Tasks; namespace NDB.Security.Authentication.Identity { public class IdentityAuthenticationHandler : AuthenticationHandler { private readonly IIdentityService _identityService; private readonly IAuthenticationOptions _authenticationOptions; public IdentityAuthenticationHandler(IOptionsMonitor options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock, IIdentityService identityService, IAuthenticationOptions authenticationOptions) : base(options, logger, encoder, clock) { _identityService = identityService; _authenticationOptions = authenticationOptions; } protected override async Task HandleAuthenticateAsync() { if (!Request.Headers.ContainsKey("Authorization")) { var authenticateAsGuest = _authenticationOptions.AuthenticateAsGuest?.Invoke(Request) ?? false; if (authenticateAsGuest) { var guestTicket = GetAuthenticationTicket(new User() { UserId = _authenticationOptions.GuestUserId, UserName = _authenticationOptions.GuestUserName }); return AuthenticateResult.Success(guestTicket); } return AuthenticateResult.Fail("Missing Authorization Header"); } User user; try { var authorizationHeader = AuthenticationHeaderValue.Parse(Request.Headers["Authorization"]); var token = authorizationHeader.Parameter; user = await _identityService.Authorize(token); } catch { return AuthenticateResult.Fail("Invalid Authorization Header"); } if (user == null) return AuthenticateResult.Fail("Invalid Username or Password"); var ticket = GetAuthenticationTicket(user); return AuthenticateResult.Success(ticket); } private AuthenticationTicket GetAuthenticationTicket(User user) { var claims = new[] { new Claim(ClaimTypes.NameIdentifier, user.UserId.ToString()), new Claim(ClaimTypes.Name, user.UserName), }; var identity = new ClaimsIdentity(claims, Scheme.Name); var principal = new ClaimsPrincipal(identity); var ticket = new AuthenticationTicket(principal, Scheme.Name); return ticket; } } }