40 lines
No EOL
1.3 KiB
C#
40 lines
No EOL
1.3 KiB
C#
using AspNetCore.Authentication.ApiKey;
|
|
using StalwartSimpleLoginMiddleware.Models;
|
|
using StalwartSimpleLoginMiddleware.Repositories;
|
|
|
|
namespace StalwartSimpleLoginMiddleware.Services;
|
|
|
|
public class ApiKeyProvider : ApiKeyEvents
|
|
{
|
|
public ApiKeyProvider()
|
|
{
|
|
OnValidateKey = OnValidateKeyAsync;
|
|
}
|
|
|
|
private static async Task OnValidateKeyAsync(ApiKeyValidateKeyContext context)
|
|
{
|
|
var apiKeyRepository = context.HttpContext.RequestServices.GetRequiredService<IApiKeyRepository>();
|
|
var apiKey = await apiKeyRepository.GetApiKeyAsync(context.ApiKey);
|
|
|
|
if (apiKey == null || !apiKey.Key.Equals(context.ApiKey, StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
context.ValidationFailed();
|
|
return;
|
|
}
|
|
|
|
context.ValidationSucceeded(apiKey.OwnerName, apiKey.Claims);
|
|
|
|
var apiKeyAccessor = context.HttpContext.RequestServices.GetRequiredService<IApiKeyAccessor>();
|
|
apiKeyAccessor.ApiKey = apiKey;
|
|
apiKeyAccessor.Metadata = await apiKeyRepository.GetMetadataAsync(context.ApiKey);
|
|
}
|
|
|
|
public override async Task HandleChallengeAsync(ApiKeyHandleChallengeContext context)
|
|
{
|
|
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
|
|
|
|
await context.Response.WriteAsync("{\"Unauthorized\": 401}");
|
|
|
|
context.Handled();
|
|
}
|
|
} |