Add project files
This commit is contained in:
parent
4dafed3553
commit
8cf01ead74
40 changed files with 3967 additions and 0 deletions
40
StalwartSimpleLoginMiddleware/Services/ApiKeyProvider.cs
Normal file
40
StalwartSimpleLoginMiddleware/Services/ApiKeyProvider.cs
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
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();
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue