btcpayserver/BTCPayServer/Security/GreenField/APIKeyExtensions.cs

67 lines
2.7 KiB
C#
Raw Normal View History

2020-03-27 04:58:45 +01:00
using System;
using System.Linq;
using BTCPayServer.Abstractions.Constants;
2020-03-27 04:58:45 +01:00
using BTCPayServer.Client;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Primitives;
2022-01-14 05:05:23 +01:00
namespace BTCPayServer.Security.Greenfield
2020-03-27 04:58:45 +01:00
{
public static class APIKeyExtensions
{
public static bool GetAPIKey(this HttpContext httpContext, out StringValues apiKey)
{
2021-12-27 05:15:43 +01:00
apiKey = default;
2020-03-27 04:58:45 +01:00
if (httpContext.Request.Headers.TryGetValue("Authorization", out var value) &&
value.ToString().StartsWith("token ", StringComparison.InvariantCultureIgnoreCase))
{
apiKey = value.ToString().Substring("token ".Length);
return true;
}
return false;
}
public static AuthenticationBuilder AddAPIKeyAuthentication(this AuthenticationBuilder builder)
{
2022-01-14 05:05:23 +01:00
builder.AddScheme<GreenfieldAuthenticationOptions, APIKeysAuthenticationHandler>(AuthenticationSchemes.GreenfieldAPIKeys,
o => { });
2022-01-14 05:05:23 +01:00
builder.AddScheme<GreenfieldAuthenticationOptions, BasicAuthenticationHandler>(AuthenticationSchemes.GreenfieldBasic,
2020-03-27 04:58:45 +01:00
o => { });
return builder;
}
public static IServiceCollection AddAPIKeyAuthentication(this IServiceCollection serviceCollection)
{
serviceCollection.AddSingleton<APIKeyRepository>();
2022-01-14 05:05:23 +01:00
serviceCollection.AddScoped<IAuthorizationHandler, GreenfieldAuthorizationHandler>();
serviceCollection.AddScoped<IAuthorizationHandler, LocalGreenfieldAuthorizationHandler>();
2020-03-27 04:58:45 +01:00
return serviceCollection;
}
public static string[] GetPermissions(this AuthorizationHandlerContext context)
{
return context.User.Claims.Where(c =>
2022-01-14 05:05:23 +01:00
c.Type.Equals(GreenfieldConstants.ClaimTypes.Permission, StringComparison.InvariantCultureIgnoreCase))
2020-03-27 04:58:45 +01:00
.Select(claim => claim.Value).ToArray();
}
public static bool HasPermission(this AuthorizationHandlerContext context, Permission permission)
{
foreach (var claim in context.User.Claims.Where(c =>
2022-01-14 05:05:23 +01:00
c.Type.Equals(GreenfieldConstants.ClaimTypes.Permission, StringComparison.InvariantCultureIgnoreCase)))
2020-03-27 04:58:45 +01:00
{
if (Permission.TryParse(claim.Value, out var claimPermission))
{
if (claimPermission.Contains(permission))
{
return true;
}
}
}
return false;
}
}
}