2020-03-27 12:58:45 +09:00
|
|
|
using System.Collections.Generic;
|
|
|
|
using System.Linq;
|
|
|
|
using System.Security.Claims;
|
|
|
|
using System.Text.Encodings.Web;
|
|
|
|
using System.Threading.Tasks;
|
|
|
|
using BTCPayServer.Client;
|
|
|
|
using BTCPayServer.Data;
|
|
|
|
using Microsoft.AspNetCore.Authentication;
|
|
|
|
using Microsoft.AspNetCore.Identity;
|
|
|
|
using Microsoft.Extensions.Logging;
|
|
|
|
using Microsoft.Extensions.Options;
|
|
|
|
|
|
|
|
namespace BTCPayServer.Security.GreenField
|
|
|
|
{
|
2020-03-27 13:06:41 +09:00
|
|
|
public class APIKeysAuthenticationHandler : AuthenticationHandler<GreenFieldAuthenticationOptions>
|
2020-03-27 12:58:45 +09:00
|
|
|
{
|
|
|
|
private readonly APIKeyRepository _apiKeyRepository;
|
|
|
|
private readonly IOptionsMonitor<IdentityOptions> _identityOptions;
|
|
|
|
private readonly UserManager<ApplicationUser> _userManager;
|
|
|
|
|
2020-03-27 13:06:41 +09:00
|
|
|
public APIKeysAuthenticationHandler(
|
2020-03-27 12:58:45 +09:00
|
|
|
APIKeyRepository apiKeyRepository,
|
|
|
|
IOptionsMonitor<IdentityOptions> identityOptions,
|
|
|
|
IOptionsMonitor<GreenFieldAuthenticationOptions> options,
|
|
|
|
ILoggerFactory logger,
|
|
|
|
UrlEncoder encoder,
|
|
|
|
ISystemClock clock,
|
|
|
|
UserManager<ApplicationUser> userManager) : base(options, logger, encoder, clock)
|
|
|
|
{
|
|
|
|
_apiKeyRepository = apiKeyRepository;
|
|
|
|
_identityOptions = identityOptions;
|
|
|
|
_userManager = userManager;
|
|
|
|
}
|
|
|
|
|
|
|
|
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
|
|
|
|
{
|
|
|
|
if (!Context.Request.HttpContext.GetAPIKey(out var apiKey) || string.IsNullOrEmpty(apiKey))
|
|
|
|
return AuthenticateResult.NoResult();
|
|
|
|
|
2020-08-19 14:46:45 +02:00
|
|
|
var key = await _apiKeyRepository.GetKey(apiKey, true);
|
2020-03-27 12:58:45 +09:00
|
|
|
|
|
|
|
if (key == null)
|
|
|
|
{
|
|
|
|
return AuthenticateResult.Fail("ApiKey authentication failed");
|
|
|
|
}
|
|
|
|
List<Claim> claims = new List<Claim>();
|
|
|
|
claims.Add(new Claim(_identityOptions.CurrentValue.ClaimsIdentity.UserIdClaimType, key.UserId));
|
2021-12-31 16:59:02 +09:00
|
|
|
|
2020-08-19 14:46:45 +02:00
|
|
|
claims.AddRange((await _userManager.GetRolesAsync(key.User)).Select(s => new Claim(_identityOptions.CurrentValue.ClaimsIdentity.RoleClaimType, s)));
|
2020-04-02 08:59:20 +02:00
|
|
|
claims.AddRange(Permission.ToPermissions(key.GetBlob().Permissions).Select(permission =>
|
2020-03-27 12:58:45 +09:00
|
|
|
new Claim(GreenFieldConstants.ClaimTypes.Permission, permission.ToString())));
|
|
|
|
return AuthenticateResult.Success(new AuthenticationTicket(
|
|
|
|
new ClaimsPrincipal(new ClaimsIdentity(claims, GreenFieldConstants.AuthenticationType)),
|
|
|
|
GreenFieldConstants.AuthenticationType));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|