netmash/NDB.Security.Authentication.../IdentityAuthenticationHandl...

74 lines
2.9 KiB
C#
Raw Normal View History

2020-12-21 22:58:40 +02:00
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;
2020-12-21 22:58:40 +02:00
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<AuthenticationSchemeOptions>
2020-12-21 22:58:40 +02:00
{
private readonly IIdentityService _identityService;
private readonly IAuthenticationOptions _authenticationOptions;
2020-12-21 22:58:40 +02:00
public IdentityAuthenticationHandler(IOptionsMonitor<AuthenticationSchemeOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock, IIdentityService identityService, IAuthenticationOptions authenticationOptions)
2020-12-21 22:58:40 +02:00
: base(options, logger, encoder, clock)
{
_identityService = identityService;
_authenticationOptions = authenticationOptions;
2020-12-21 22:58:40 +02:00
}
protected override async Task<AuthenticateResult> 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);
}
2020-12-21 22:58:40 +02:00
return AuthenticateResult.Fail("Missing Authorization Header");
}
2020-12-21 22:58:40 +02:00
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)
{
2020-12-21 22:58:40 +02:00
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;
2020-12-21 22:58:40 +02:00
}
}
}