- Refactor XApiAccountEndpoint and Add Application Routes into it ... - Refactor IXIdentityProvider and XIdentityProvider and Add Support for Calling ApplicationController on xIds and Retrieve Responses of it ... - Add XBaseTestIdentity Controller and Add Support for Test ApiKey Based Authorization on it ...
201 lines
6.8 KiB
C#
201 lines
6.8 KiB
C#
using System;
|
|
using IdentityModel;
|
|
using System.Threading;
|
|
using xCommons.Constants;
|
|
using xCommons.Extensions;
|
|
using xExceptions.Constants;
|
|
using xIdentityModels.Models;
|
|
using System.Security.Claims;
|
|
using System.Threading.Tasks;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
using xIdentityModels.Constants;
|
|
using System.Collections.Generic;
|
|
using xIdentityService.Constants;
|
|
using xIdentityService.Interfaces;
|
|
using Microsoft.AspNetCore.Mvc.Filters;
|
|
using Microsoft.AspNetCore.Authorization;
|
|
using Microsoft.AspNetCore.Http.Features;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
|
|
namespace xIdentityService.Attributes
|
|
{
|
|
[AttributeUsage(
|
|
AttributeTargets.Class | AttributeTargets.Method,
|
|
AllowMultiple = false,
|
|
Inherited = true
|
|
)]
|
|
public class XApiKeyAccessAttribute : AuthorizeAttribute, IAuthorizationFilter
|
|
{
|
|
/// <summary>
|
|
/// Optional allowed scopes. If empty, no scope enforcement.
|
|
/// </summary>
|
|
public XApiKeyScope[] Scopes { get; set; }
|
|
|
|
public XApiKeyAccessAttribute(
|
|
XApiKeyScope[] scopes = null
|
|
)
|
|
{
|
|
//
|
|
if (!scopes.HasChild())
|
|
{
|
|
scopes = [XApiKeyScope.Read];
|
|
}
|
|
|
|
//
|
|
Scopes = scopes;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Authorization Filtering ...
|
|
/// </summary>
|
|
/// <param name="context"></param>
|
|
public void OnAuthorization(AuthorizationFilterContext context)
|
|
{
|
|
Task.FromResult(OnAuthorizationAsync(context));
|
|
}
|
|
|
|
/// <summary>
|
|
/// Handle Authorization Filtering Using Tasks ...
|
|
/// </summary>
|
|
/// <param name="context"></param>
|
|
/// <param name="cancellationToken"></param>
|
|
/// <returns></returns>
|
|
private async Task OnAuthorizationAsync(
|
|
AuthorizationFilterContext context,
|
|
CancellationToken cancellationToken = default
|
|
)
|
|
{
|
|
//
|
|
// Access HttpContext ...
|
|
var http = context.HttpContext;
|
|
var error = XException.NotAuthorized.ToXError();
|
|
var apiKeyAuthentication = XAuthenticationScheme.XApiKey.GetStringValue();
|
|
|
|
//
|
|
try
|
|
{
|
|
//
|
|
// Obtain the endpoint currently being executed
|
|
var endpointFeature = http.Features.Get<IEndpointFeature>();
|
|
var endpoint = endpointFeature?.Endpoint;
|
|
if (endpoint.IsNull() ||
|
|
endpointFeature.IsNull()
|
|
)
|
|
{
|
|
//
|
|
error.Message = "Endpoint not Accessible ...";
|
|
context.Result = new UnauthorizedObjectResult(error);
|
|
return;
|
|
}
|
|
|
|
//
|
|
// Retrieve Identity Provider Service from DI ...
|
|
var identityService = http.RequestServices
|
|
.GetService<IXIdentityProvider>();
|
|
if (identityService.IsNull())
|
|
{
|
|
//
|
|
error.Message = "Api Key Service not Registered ...";
|
|
context.Result = new UnauthorizedObjectResult(error);
|
|
return;
|
|
}
|
|
|
|
//
|
|
// Checking Header ...
|
|
var apiKeyHeader = XHeader.ApiKey.GetStringValue();
|
|
if (!http.Request.Headers.ContainsKey(apiKeyHeader))
|
|
{
|
|
//
|
|
error.Message = "ApiKey not Exists ...";
|
|
context.Result = new UnauthorizedObjectResult(error);
|
|
return;
|
|
}
|
|
|
|
//
|
|
// Extract ApiKey from Header ...
|
|
var apiKey = http.Request.Headers[apiKeyHeader].ToString();
|
|
if (apiKey.IsNullOrEmpty())
|
|
{
|
|
//
|
|
error.Message = "ApiKey not Provided ...";
|
|
context.Result = new UnauthorizedObjectResult(error);
|
|
return;
|
|
}
|
|
|
|
//
|
|
// Extract Client IP ...
|
|
var clientIP = http.Request.HttpContext.Connection.RemoteIpAddress?.ToString();
|
|
var scopes =
|
|
!Scopes.HasChild()
|
|
? string.Empty
|
|
: Scopes.ToListString();
|
|
|
|
//
|
|
// Prepare Validation Request ...
|
|
var validationRequest = new XApiKeyValidationRequest
|
|
{
|
|
ApiKey = apiKey,
|
|
ClientIP = clientIP,
|
|
RequiredScope = scopes
|
|
};
|
|
|
|
//
|
|
// Validating ApiKey ...
|
|
var validationResponse = identityService.ValidateApiKey(
|
|
request: validationRequest,
|
|
cancellationToken: cancellationToken
|
|
)
|
|
.GetAwaiter()
|
|
.GetResult();
|
|
if (validationResponse.Errors.HasChild())
|
|
{
|
|
//
|
|
var message = validationResponse.Errors.ToListString(',');
|
|
error.Message = message;
|
|
context.Result = new UnauthorizedObjectResult(error);
|
|
return;
|
|
}
|
|
|
|
//
|
|
// Creating Claims ...
|
|
var claims = new List<Claim> {
|
|
//
|
|
// Owner Identifier of API Key ...
|
|
new(ClaimTypes.Name, validationResponse.OwnerId),
|
|
new(JwtClaimTypes.Subject, validationResponse.OwnerId),
|
|
//
|
|
// Application Id ...
|
|
new(XCustomClaims.ApplicationId, validationResponse.ApplicationId.ToString()),
|
|
//
|
|
// Authentication Type ...
|
|
new(XCustomClaims.AuthType, apiKeyAuthentication),
|
|
};
|
|
|
|
//
|
|
// Add Scopes ...
|
|
if (validationResponse.Scopes != null)
|
|
{
|
|
//
|
|
foreach (var scope in validationResponse.Scopes)
|
|
{
|
|
claims.Add(new Claim(JwtClaimTypes.Scope, scope));
|
|
}
|
|
}
|
|
|
|
//
|
|
// Create Principal and Ticket ...
|
|
var identity = new ClaimsIdentity(claims, apiKeyAuthentication);
|
|
var principal = new ClaimsPrincipal(identity);
|
|
|
|
//
|
|
http.User = principal;
|
|
}
|
|
catch
|
|
{
|
|
//
|
|
error.Message = "ApiKey authorization failed ...";
|
|
context.Result = new UnauthorizedObjectResult(error);
|
|
}
|
|
}
|
|
}
|
|
} |