151 lines
5.0 KiB
C#
151 lines
5.0 KiB
C#
using System;
|
|
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 xIdentityModels.Extensions;
|
|
using xIdentityService.Constants;
|
|
using xIdentityService.Interfaces;
|
|
using Microsoft.AspNetCore.Mvc.Filters;
|
|
using Microsoft.AspNetCore.Authorization;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
|
|
namespace xIdentityService.Attributes
|
|
{
|
|
[AttributeUsage(
|
|
AttributeTargets.Class | AttributeTargets.Method,
|
|
AllowMultiple = false,
|
|
Inherited = true
|
|
)]
|
|
public class XApiKeyAccessAttribute : AuthorizeAttribute, IAsyncAuthorizationFilter
|
|
{
|
|
/// <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;
|
|
|
|
//
|
|
Policy = $"{XIdentityServiceConstants.PolicyCacheKeyPrefix}:{string.Join(";", Scopes)}";
|
|
}
|
|
|
|
/// <summary>
|
|
/// Authorization Filtering ...
|
|
/// </summary>
|
|
/// <param name="context"></param>
|
|
public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
|
|
{
|
|
//
|
|
// Access HttpContext ...
|
|
var http = context.HttpContext;
|
|
var cancellationToken = http.RequestAborted;
|
|
var error = XException.NotAuthorized.ToXError();
|
|
var apiKeyAuthentication = XAuthenticationScheme.XApiKey.GetStringValue();
|
|
|
|
//
|
|
try
|
|
{
|
|
//
|
|
// 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 = validationResponse.ToXClaims();
|
|
|
|
//
|
|
// 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);
|
|
}
|
|
}
|
|
}
|
|
} |