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

133 lines
5.1 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;
using c = NDB.Security.Authentication.Identity.Constants;
using System.Collections.Generic;
using System.Linq;
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()
{
var token = GetAuthorizationToken();
if (token != null)
{
TokenCore tokenCore;
try
{
tokenCore = await _identityService.Authorize(token);
}
catch
{
return AuthenticateResult.Fail("Invalid authorization");
}
if (tokenCore == null)
return AuthenticateResult.Fail("Invalid token");
var ticket = GetAuthenticationTicket(tokenCore);
return AuthenticateResult.Success(ticket);
}
2020-12-21 22:58:40 +02:00
var authenticateAsGuest = _authenticationOptions.AuthenticateAsGuest?.Invoke(Request) ?? false;
if (authenticateAsGuest)
{
var guestTicket = GetGuestAuthenticationTicket(_authenticationOptions.GuestUserId, _authenticationOptions.GuestUserName);
return AuthenticateResult.Success(guestTicket);
}
return AuthenticateResult.Fail("Missing authorization header");
}
private string GetAuthorizationToken()
{
if (Request.Headers.ContainsKey("Authorization"))
2020-12-21 22:58:40 +02:00
{
var authorizationHeader = AuthenticationHeaderValue.Parse(Request.Headers["Authorization"]);
var token = authorizationHeader.Parameter;
return token;
2020-12-21 22:58:40 +02:00
}
if (_authenticationOptions.AcceptTokenFromQuery
&& Request.Query.Count > 0
&& Request.Query.ContainsKey(c.QueryParams.Token))
2020-12-21 22:58:40 +02:00
{
var token = Request.Query[c.QueryParams.Token];
return token.ToString();
2020-12-21 22:58:40 +02:00
}
return null;
}
private AuthenticationTicket GetGuestAuthenticationTicket(int guestId, string guestName)
{
2020-12-21 22:58:40 +02:00
var claims = new[] {
new Claim(ClaimTypes.NameIdentifier, guestId.ToString()),
new Claim(ClaimTypes.Name, guestName),
new Claim(Constants.ClaimTypes.IsGuestUser, bool.TrueString)
2020-12-21 22:58:40 +02:00
};
var ticket = GetAuthenticationTicket(claims);
return ticket;
}
private AuthenticationTicket GetAuthenticationTicket(TokenCore tokenCore)
{
var claimCollection = new Dictionary<string, string>()
{
{ ClaimTypes.NameIdentifier, tokenCore.UserId.ToString() },
{ ClaimTypes.Name, tokenCore.UserName },
{ Constants.ClaimTypes.UserName, tokenCore.UserName }
};
if (tokenCore.FirstName != null)
claimCollection.Add(Constants.ClaimTypes.FirstName, tokenCore.FirstName);
if (tokenCore.LastName != null)
claimCollection.Add(Constants.ClaimTypes.LastName, tokenCore.LastName);
if (tokenCore.ProfilePictureUrl != null)
claimCollection.Add(Constants.ClaimTypes.ProfilePictureUrl, tokenCore.ProfilePictureUrl);
if (tokenCore.Email != null)
claimCollection.Add(ClaimTypes.Email, tokenCore.Email);
if (tokenCore.Claims != null && tokenCore.Claims.Any())
{
foreach (var claim in tokenCore.Claims)
claimCollection.Add(claim.Key, claim.Value);
}
var claims = claimCollection.Select(z => new Claim(z.Key, z.Value)).ToArray();
var ticket = GetAuthenticationTicket(claims);
return ticket;
}
private AuthenticationTicket GetAuthenticationTicket(Claim[] claims)
{
2020-12-21 22:58:40 +02:00
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
}
}
}