2022-10-12 15:19:33 +02:00
|
|
|
#nullable enable
|
|
|
|
using System;
|
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;
|
2024-01-31 06:45:54 +01:00
|
|
|
using BTCPayServer.Services;
|
2020-03-27 12:58:45 +09:00
|
|
|
using Microsoft.AspNetCore.Authentication;
|
|
|
|
using Microsoft.AspNetCore.Identity;
|
|
|
|
using Microsoft.Extensions.Logging;
|
|
|
|
using Microsoft.Extensions.Options;
|
2022-10-12 15:19:33 +02:00
|
|
|
using Microsoft.Net.Http.Headers;
|
2020-03-27 12:58:45 +09:00
|
|
|
|
2022-01-14 13:05:23 +09:00
|
|
|
namespace BTCPayServer.Security.Greenfield
|
2020-03-27 12:58:45 +09:00
|
|
|
{
|
2022-01-14 13:05:23 +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,
|
2022-01-14 13:05:23 +09:00
|
|
|
IOptionsMonitor<GreenfieldAuthenticationOptions> options,
|
2020-03-27 12:58:45 +09:00
|
|
|
ILoggerFactory logger,
|
|
|
|
UrlEncoder encoder,
|
2023-11-28 23:20:03 +09:00
|
|
|
UserManager<ApplicationUser> userManager) : base(options, logger, encoder)
|
2020-03-27 12:58:45 +09:00
|
|
|
{
|
|
|
|
_apiKeyRepository = apiKeyRepository;
|
|
|
|
_identityOptions = identityOptions;
|
|
|
|
_userManager = userManager;
|
|
|
|
}
|
2022-10-12 15:19:33 +02:00
|
|
|
protected override Task HandleChallengeAsync(AuthenticationProperties properties)
|
|
|
|
{
|
|
|
|
// This one deserve some explanation...
|
|
|
|
// Some routes have this authorization.
|
|
|
|
// [Authorize(AuthenticationSchemes = AuthenticationSchemes.Cookie + "," + AuthenticationSchemes.Greenfield)]
|
|
|
|
// This is meant for API routes that we wish to access by greenfield but also via the browser for documentation purpose (say /misc/rate-sources)
|
|
|
|
// Now, if we aren't logged nor authenticated via greenfield, the AuthenticationHandlers get challenged.
|
|
|
|
// The last handler to be challenged is the CookieAuthenticationHandler, which instruct to handle the challenge as a redirection to
|
|
|
|
// the login page.
|
|
|
|
// But this isn't what we want when we call the API programmatically, instead we want an error 401 with a json error message.
|
|
|
|
// This hack modify a request's header to trick the CookieAuthenticationHandler to not do a redirection.
|
2023-11-28 23:20:03 +09:00
|
|
|
if (!Request.Headers.Accept.Any(s => s is string && s.StartsWith("text/html", StringComparison.OrdinalIgnoreCase)))
|
2022-10-12 15:19:33 +02:00
|
|
|
Request.Headers.XRequestedWith = new Microsoft.Extensions.Primitives.StringValues("XMLHttpRequest");
|
|
|
|
return base.HandleChallengeAsync(properties);
|
|
|
|
}
|
|
|
|
private bool IsJson(string contentType)
|
|
|
|
{
|
|
|
|
return contentType?.StartsWith("application/json", StringComparison.OrdinalIgnoreCase) is true;
|
|
|
|
}
|
2020-03-27 12:58:45 +09:00
|
|
|
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);
|
2024-01-31 06:45:54 +01:00
|
|
|
if (!UserService.TryCanLogin(key?.User, out var error))
|
2020-03-27 12:58:45 +09:00
|
|
|
{
|
2024-01-31 06:45:54 +01:00
|
|
|
return AuthenticateResult.Fail($"ApiKey authentication failed: {error}");
|
2020-03-27 12:58:45 +09:00
|
|
|
}
|
2021-12-31 16:59:02 +09:00
|
|
|
|
2024-01-31 06:45:54 +01:00
|
|
|
var claims = new List<Claim> { new (_identityOptions.CurrentValue.ClaimsIdentity.UserIdClaimType, key.UserId) };
|
2020-08-19 14:46:45 +02:00
|
|
|
claims.AddRange((await _userManager.GetRolesAsync(key.User)).Select(s => new Claim(_identityOptions.CurrentValue.ClaimsIdentity.RoleClaimType, s)));
|
2023-02-21 15:06:34 +09:00
|
|
|
claims.AddRange(Permission.ToPermissions(key.GetBlob()?.Permissions ?? Array.Empty<string>()).Select(permission =>
|
2022-01-14 13:05:23 +09:00
|
|
|
new Claim(GreenfieldConstants.ClaimTypes.Permission, permission.ToString())));
|
2020-03-27 12:58:45 +09:00
|
|
|
return AuthenticateResult.Success(new AuthenticationTicket(
|
2022-01-14 13:05:23 +09:00
|
|
|
new ClaimsPrincipal(new ClaimsIdentity(claims, GreenfieldConstants.AuthenticationType)),
|
|
|
|
GreenfieldConstants.AuthenticationType));
|
2020-03-27 12:58:45 +09:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|