101 lines
3.2 KiB
C#
101 lines
3.2 KiB
C#
using System.Linq;
|
|
using IdentityModel;
|
|
using xIds.Interfaces;
|
|
using xCommons.Extensions;
|
|
using System.Threading.Tasks;
|
|
using System.Security.Claims;
|
|
using System.Text.Encodings.Web;
|
|
using xIdentityService.Constants;
|
|
using Microsoft.Extensions.Options;
|
|
using Microsoft.Extensions.Logging;
|
|
using Microsoft.AspNetCore.Authentication;
|
|
|
|
namespace xIds.Providers
|
|
{
|
|
/// <summary>
|
|
/// an Authentication Handler for ApiKey's based App's ...
|
|
/// </summary>
|
|
public class XApiKeyAuthenticationHandler : AuthenticationHandler<AuthenticationSchemeOptions>
|
|
{
|
|
private readonly IXApplicationProvider applicationProvider;
|
|
|
|
//
|
|
public string HeaderName { get; } = XHeader.ApiKey.GetStringValue();
|
|
public string AuthenticationScheme { get; } = XAuthenticationScheme.XApiKey.GetStringValue();
|
|
|
|
public XApiKeyAuthenticationHandler(
|
|
UrlEncoder encoder,
|
|
ISystemClock clock,
|
|
ILoggerFactory logger,
|
|
IXApplicationProvider applicationProvider,
|
|
IOptionsMonitor<AuthenticationSchemeOptions> options
|
|
) : base(options, logger, encoder, clock)
|
|
{
|
|
this.applicationProvider = applicationProvider;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Handle Authentication ...
|
|
/// </summary>
|
|
/// <returns></returns>
|
|
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
|
|
{
|
|
//
|
|
var apiKey =
|
|
!Request.Headers.ContainsKey(HeaderName)
|
|
? string.Empty
|
|
: Request.Headers[HeaderName].ToString();
|
|
if (apiKey.IsNullOrEmpty())
|
|
{
|
|
return AuthenticateResult.NoResult();
|
|
}
|
|
|
|
//
|
|
var clientIP = Request.HttpContext.Connection.RemoteIpAddress?.ToString();
|
|
|
|
//
|
|
var validationResult = await applicationProvider.ValidateApiKey(
|
|
apiKey: apiKey,
|
|
clientIP: clientIP
|
|
);
|
|
var isValid = !validationResult.Errors.HasChild();
|
|
if (!isValid)
|
|
{
|
|
//
|
|
var message = validationResult.Errors.ToListString('\n');
|
|
return AuthenticateResult.Fail(message);
|
|
}
|
|
|
|
//
|
|
var claims = new[]
|
|
{
|
|
new Claim(ClaimTypes.Name, validationResult.OwnerId),
|
|
new Claim("application_id", validationResult.ApplicationId.ToString()),
|
|
new Claim("auth_type", "apikey"),
|
|
new Claim(JwtClaimTypes.Scope, "apikey"),
|
|
};
|
|
|
|
//
|
|
var scopeClaims = validationResult.Scopes
|
|
.Select(s => new Claim(JwtClaimTypes.Scope, s));
|
|
|
|
//
|
|
var identity = new ClaimsIdentity(
|
|
claims.Union(scopeClaims),
|
|
AuthenticationScheme
|
|
);
|
|
|
|
//
|
|
var principal = new ClaimsPrincipal(identity);
|
|
|
|
//
|
|
var ticket = new AuthenticationTicket(
|
|
principal,
|
|
AuthenticationScheme
|
|
);
|
|
|
|
//
|
|
return AuthenticateResult.Success(ticket);
|
|
}
|
|
}
|
|
} |