Merge pull request #1403 from Kukks/basic-auth

Greenfield API: Basic Auth
This commit is contained in:
Nicolas Dorier 2020-03-25 21:00:14 +09:00 committed by GitHub
commit e36338d903
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
11 changed files with 138 additions and 41 deletions

View File

@ -14,6 +14,8 @@ namespace BTCPayServer.Client
{
private readonly string _apiKey;
private readonly Uri _btcpayHost;
private readonly string _username;
private readonly string _password;
private readonly HttpClient _httpClient;
public string APIKey => _apiKey;
@ -31,6 +33,15 @@ namespace BTCPayServer.Client
_btcpayHost = btcpayHost;
_httpClient = httpClient ?? new HttpClient();
}
public BTCPayServerClient(Uri btcpayHost, string username, string password, HttpClient httpClient = null)
{
_apiKey = APIKey;
_btcpayHost = btcpayHost;
_username = username;
_password = password;
_httpClient = httpClient ?? new HttpClient();
}
protected void HandleResponse(HttpResponseMessage message)
{
@ -56,6 +67,10 @@ namespace BTCPayServer.Client
var httpRequest = new HttpRequestMessage(method ?? HttpMethod.Get, uriBuilder.Uri);
if (_apiKey != null)
httpRequest.Headers.Authorization = new AuthenticationHeaderValue("token", _apiKey);
else if (!string.IsNullOrEmpty(_username))
{
httpRequest.Headers.Authorization = new AuthenticationHeaderValue("Basic", System.Convert.ToBase64String(Encoding.ASCII.GetBytes(_username + ":" + _password)));
}
return httpRequest;

View File

@ -38,15 +38,23 @@ namespace BTCPayServer.Tests
user.GrantAccess();
await user.MakeAdmin();
var client = await user.CreateClient(Policies.Unrestricted);
var clientBasic = await user.CreateClient();
//Get current api key
var apiKeyData = await client.GetCurrentAPIKeyInfo();
Assert.NotNull(apiKeyData);
Assert.Equal(client.APIKey, apiKeyData.ApiKey);
Assert.Single(apiKeyData.Permissions);
//a client using Basic Auth has no business here
await AssertHttpError(404, async () => await clientBasic.GetCurrentAPIKeyInfo());
//revoke current api key
await client.RevokeCurrentAPIKeyInfo();
await AssertHttpError(401, async () => await client.GetCurrentAPIKeyInfo());
//a client using Basic Auth has no business here
await AssertHttpError(404, async () => await clientBasic.RevokeCurrentAPIKeyInfo());
}
}
@ -108,12 +116,14 @@ namespace BTCPayServer.Tests
user1Acc.UserId = user1.Id;
user1Acc.IsAdmin = false;
var user1Client = await user1Acc.CreateClient(Policies.CanModifyServerSettings);
// User1 trying to get server management would still fail to create user
await AssertHttpError(403, async () => await user1Client.CreateUser(new CreateApplicationUserRequest() { Email = "test8@gmail.com", Password = "afewfoiewiou" }));
// User1 should be able to create user if subscription unlocked
await settings.UpdateSetting<PoliciesSettings>(new PoliciesSettings() { LockSubscription = false });
await user1Client.CreateUser(new CreateApplicationUserRequest() { Email = "test8@gmail.com", Password = "afewfoiewiou" });
// But not an admin
await AssertHttpError(403, async () => await user1Client.CreateUser(new CreateApplicationUserRequest() { Email = "admin8@gmail.com", Password = "afewfoiewiou", IsAdministrator = true }));
}
@ -139,6 +149,7 @@ namespace BTCPayServer.Tests
var clientProfile = await user.CreateClient(Policies.CanModifyProfile);
var clientServer = await user.CreateClient(Policies.CanCreateUser, Policies.CanViewProfile);
var clientInsufficient = await user.CreateClient(Policies.CanModifyStoreSettings);
var clientBasic = await user.CreateClient();
var apiKeyProfileUserData = await clientProfile.GetCurrentUser();
@ -149,6 +160,7 @@ namespace BTCPayServer.Tests
await Assert.ThrowsAsync<HttpRequestException>(async () => await clientInsufficient.GetCurrentUser());
await clientServer.GetCurrentUser();
await clientProfile.GetCurrentUser();
await clientBasic.GetCurrentUser();
await Assert.ThrowsAsync<HttpRequestException>(async () => await clientInsufficient.CreateUser(new CreateApplicationUserRequest()
{
@ -163,6 +175,13 @@ namespace BTCPayServer.Tests
});
Assert.NotNull(newUser);
var newUser2 = await clientBasic.CreateUser(new CreateApplicationUserRequest()
{
Email = $"{Guid.NewGuid()}@g.com",
Password = Guid.NewGuid().ToString()
});
Assert.NotNull(newUser2);
await Assert.ThrowsAsync<HttpRequestException>(async () => await clientServer.CreateUser(new CreateApplicationUserRequest()
{
Email = $"{Guid.NewGuid()}",

View File

@ -49,6 +49,11 @@ namespace BTCPayServer.Tests
IsAdmin = true;
}
public async Task<BTCPayServerClient> CreateClient()
{
return new BTCPayServerClient(parent.PayTester.ServerUri, RegisterDetails.Email, RegisterDetails.Password);
}
public async Task<BTCPayServerClient> CreateClient(params string[] permissions)
{
var manageController = parent.PayTester.GetController<ManageController>(UserId, StoreId, IsAdmin);

View File

@ -102,6 +102,13 @@ namespace BTCPayServer.Tests
var schema = JSchema.Parse(await resp.Content.ReadAsStringAsync());
IList<ValidationError> errors;
bool valid = swagger.IsValid(schema, out errors);
//the schema is not fully compliant to the spec. We ARE allowed to have multiple security schemas.
if (!valid && errors.Count == 1 && errors.Any(error =>
error.Path == "components.securitySchemes.Basic" && error.ErrorType == ErrorType.OneOf))
{
errors = new List<ValidationError>();
valid = true;
}
Assert.Empty(errors);
Assert.True(valid);
}

View File

@ -6,14 +6,13 @@ using BTCPayServer.Data;
using BTCPayServer.Security;
using BTCPayServer.Security.APIKeys;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
namespace BTCPayServer.Controllers.RestApi
{
[ApiController]
[Authorize(AuthenticationSchemes = AuthenticationSchemes.ApiKey)]
[Authorize(AuthenticationSchemes = AuthenticationSchemes.Greenfield)]
public class ApiKeysController : ControllerBase
{
private readonly APIKeyRepository _apiKeyRepository;
@ -28,16 +27,22 @@ namespace BTCPayServer.Controllers.RestApi
[HttpGet("~/api/v1/api-keys/current")]
public async Task<ActionResult<ApiKeyData>> GetKey()
{
ControllerContext.HttpContext.GetAPIKey(out var apiKey);
if (!ControllerContext.HttpContext.GetAPIKey(out var apiKey))
{
return NotFound();
}
var data = await _apiKeyRepository.GetKey(apiKey);
return Ok(FromModel(data));
}
[HttpDelete("~/api/v1/api-keys/current")]
[Authorize(Policy = Policies.Unrestricted, AuthenticationSchemes = AuthenticationSchemes.ApiKey)]
[Authorize(Policy = Policies.Unrestricted, AuthenticationSchemes = AuthenticationSchemes.Greenfield)]
public async Task<ActionResult<ApiKeyData>> RevokeKey()
{
ControllerContext.HttpContext.GetAPIKey(out var apiKey);
if (!ControllerContext.HttpContext.GetAPIKey(out var apiKey))
{
return NotFound();
}
await _apiKeyRepository.Remove(apiKey, _userManager.GetUserId(User));
return Ok();
}

View File

@ -2,7 +2,6 @@ using System.Threading.Tasks;
using BTCPayServer.Client;
using BTCPayServer.Data;
using BTCPayServer.Security;
using BTCPayServer.Security.APIKeys;
using BTCPayServer.Services.Stores;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
@ -15,7 +14,7 @@ namespace BTCPayServer.Controllers.RestApi
/// </summary>
[Route("api/test/apikey")]
[ApiController]
[Authorize(AuthenticationSchemes = AuthenticationSchemes.ApiKey)]
[Authorize(AuthenticationSchemes = AuthenticationSchemes.Greenfield)]
public class TestApiKeyController : ControllerBase
{
private readonly UserManager<ApplicationUser> _userManager;
@ -28,28 +27,28 @@ namespace BTCPayServer.Controllers.RestApi
}
[HttpGet("me/id")]
[Authorize(Policy = Policies.CanViewProfile, AuthenticationSchemes = AuthenticationSchemes.ApiKey)]
[Authorize(Policy = Policies.CanViewProfile, AuthenticationSchemes = AuthenticationSchemes.Greenfield)]
public string GetCurrentUserId()
{
return _userManager.GetUserId(User);
}
[HttpGet("me")]
[Authorize(Policy = Policies.CanViewProfile, AuthenticationSchemes = AuthenticationSchemes.ApiKey)]
[Authorize(Policy = Policies.CanViewProfile, AuthenticationSchemes = AuthenticationSchemes.Greenfield)]
public async Task<ApplicationUser> GetCurrentUser()
{
return await _userManager.GetUserAsync(User);
}
[HttpGet("me/is-admin")]
[Authorize(Policy = Policies.CanModifyServerSettings, AuthenticationSchemes = AuthenticationSchemes.ApiKey)]
[Authorize(Policy = Policies.CanModifyServerSettings, AuthenticationSchemes = AuthenticationSchemes.Greenfield)]
public bool AmIAnAdmin()
{
return true;
}
[HttpGet("me/stores")]
[Authorize(Policy = Policies.CanViewStoreSettings, AuthenticationSchemes = AuthenticationSchemes.ApiKey)]
[Authorize(Policy = Policies.CanViewStoreSettings, AuthenticationSchemes = AuthenticationSchemes.Greenfield)]
public StoreData[] GetCurrentUserStores()
{
return this.HttpContext.GetStoresData();
@ -57,7 +56,7 @@ namespace BTCPayServer.Controllers.RestApi
[HttpGet("me/stores/{storeId}/can-view")]
[Authorize(Policy = Policies.CanViewStoreSettings,
AuthenticationSchemes = AuthenticationSchemes.ApiKey)]
AuthenticationSchemes = AuthenticationSchemes.Greenfield)]
public bool CanViewStore(string storeId)
{
return true;
@ -65,7 +64,7 @@ namespace BTCPayServer.Controllers.RestApi
[HttpGet("me/stores/{storeId}/can-edit")]
[Authorize(Policy = Policies.CanModifyStoreSettings,
AuthenticationSchemes = AuthenticationSchemes.ApiKey)]
AuthenticationSchemes = AuthenticationSchemes.Greenfield)]
public bool CanEditStore(string storeId)
{
return true;

View File

@ -1,6 +1,4 @@
using System;
using Microsoft.Extensions.Logging;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
@ -13,7 +11,6 @@ using BTCPayServer.Security;
using BTCPayServer.Security.APIKeys;
using BTCPayServer.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;
@ -23,7 +20,7 @@ using BTCPayServer.Client;
namespace BTCPayServer.Controllers.RestApi
{
[ApiController]
[Authorize(AuthenticationSchemes = AuthenticationSchemes.ApiKey)]
[Authorize(AuthenticationSchemes = AuthenticationSchemes.Greenfield)]
public class UsersController : ControllerBase
{
private readonly UserManager<ApplicationUser> _userManager;
@ -40,8 +37,8 @@ namespace BTCPayServer.Controllers.RestApi
RoleManager<IdentityRole> roleManager, SettingsRepository settingsRepository,
EventAggregator eventAggregator,
IPasswordValidator<ApplicationUser> passwordValidator,
NicolasDorier.RateLimits.RateLimitService throttleService,
Configuration.BTCPayServerOptions options,
RateLimitService throttleService,
BTCPayServerOptions options,
IAuthorizationService authorizationService)
{
_userManager = userManager;
@ -55,7 +52,7 @@ namespace BTCPayServer.Controllers.RestApi
_authorizationService = authorizationService;
}
[Authorize(Policy = Policies.CanViewProfile, AuthenticationSchemes = AuthenticationSchemes.ApiKey)]
[Authorize(Policy = Policies.CanViewProfile, AuthenticationSchemes = AuthenticationSchemes.Greenfield)]
[HttpGet("~/api/v1/users/me")]
public async Task<ActionResult<ApplicationUserData>> GetCurrentUser()
{
@ -85,7 +82,7 @@ namespace BTCPayServer.Controllers.RestApi
// Even if subscription are unlocked, it is forbidden to create admin unauthenticated
if (anyAdmin && request.IsAdministrator is true && !isAuth)
return Forbid(AuthenticationSchemes.ApiKey);
return Forbid(AuthenticationSchemes.Greenfield);
// You are de-facto admin if there is no other admin, else you need to be auth and pass policy requirements
bool isAdmin = anyAdmin ? (await _authorizationService.AuthorizeAsync(User, null, new PolicyRequirement(Policies.CanModifyServerSettings))).Succeeded
&& (await _authorizationService.AuthorizeAsync(User, null, new PolicyRequirement(Policies.Unrestricted))).Succeeded
@ -93,14 +90,14 @@ namespace BTCPayServer.Controllers.RestApi
: true;
// You need to be admin to create an admin
if (request.IsAdministrator is true && !isAdmin)
return Forbid(AuthenticationSchemes.ApiKey);
return Forbid(AuthenticationSchemes.Greenfield);
if (!isAdmin && policies.LockSubscription)
{
// If we are not admin and subscriptions are locked, we need to check the Policies.CanCreateUser.Key permission
var canCreateUser = (await _authorizationService.AuthorizeAsync(User, null, new PolicyRequirement(Policies.CanCreateUser))).Succeeded;
if (!isAuth || !canCreateUser)
return Forbid(AuthenticationSchemes.ApiKey);
return Forbid(AuthenticationSchemes.Greenfield);
}
var user = new ApplicationUser

View File

@ -2,12 +2,12 @@
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using BTCPayServer.Client;
using BTCPayServer.Data;
using BTCPayServer.Security.Bitpay;
using BTCPayServer.Services.Stores;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Logging;
@ -19,6 +19,8 @@ namespace BTCPayServer.Security.APIKeys
{
private readonly APIKeyRepository _apiKeyRepository;
private readonly IOptionsMonitor<IdentityOptions> _identityOptions;
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly UserManager<ApplicationUser> _userManager;
public APIKeyAuthenticationHandler(
APIKeyRepository apiKeyRepository,
@ -26,13 +28,28 @@ namespace BTCPayServer.Security.APIKeys
IOptionsMonitor<APIKeyAuthenticationOptions> options,
ILoggerFactory logger,
UrlEncoder encoder,
ISystemClock clock) : base(options, logger, encoder, clock)
ISystemClock clock,
SignInManager<ApplicationUser> signInManager,
UserManager<ApplicationUser> userManager) : base(options, logger, encoder, clock)
{
_apiKeyRepository = apiKeyRepository;
_identityOptions = identityOptions;
_signInManager = signInManager;
_userManager = userManager;
}
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
var res = await HandleApiKeyAuthenticateResult();
if (res.None)
{
return await HandleBasicAuthenticateAsync();
}
return res;
}
private async Task<AuthenticateResult> HandleApiKeyAuthenticateResult()
{
if (!Context.Request.HttpContext.GetAPIKey(out var apiKey) || string.IsNullOrEmpty(apiKey))
return AuthenticateResult.NoResult();
@ -46,9 +63,38 @@ namespace BTCPayServer.Security.APIKeys
List<Claim> claims = new List<Claim>();
claims.Add(new Claim(_identityOptions.CurrentValue.ClaimsIdentity.UserIdClaimType, key.UserId));
claims.AddRange(Permission.ToPermissions(key.Permissions).Select(permission => new Claim(APIKeyConstants.ClaimTypes.Permission, permission.ToString())));
claims.AddRange(Permission.ToPermissions(key.Permissions).Select(permission =>
new Claim(APIKeyConstants.ClaimTypes.Permission, permission.ToString())));
return AuthenticateResult.Success(new AuthenticationTicket(
new ClaimsPrincipal(new ClaimsIdentity(claims, APIKeyConstants.AuthenticationType)), APIKeyConstants.AuthenticationType));
new ClaimsPrincipal(new ClaimsIdentity(claims, APIKeyConstants.AuthenticationType)),
APIKeyConstants.AuthenticationType));
}
private async Task<AuthenticateResult> HandleBasicAuthenticateAsync()
{
string authHeader = Context.Request.Headers["Authorization"];
if (authHeader == null || !authHeader.StartsWith("Basic ")) return AuthenticateResult.NoResult();
var encodedUsernamePassword = authHeader.Split(' ', 2, StringSplitOptions.RemoveEmptyEntries)[1]?.Trim();
var decodedUsernamePassword =
Encoding.UTF8.GetString(Convert.FromBase64String(encodedUsernamePassword)).Split(':');
var username = decodedUsernamePassword[0];
var password = decodedUsernamePassword[1];
var result = await _signInManager.PasswordSignInAsync(username, password, true, true);
if (!result.Succeeded) return AuthenticateResult.Fail(result.ToString());
var user = await _userManager.FindByNameAsync(username);
var claims = new List<Claim>()
{
new Claim(_identityOptions.CurrentValue.ClaimsIdentity.UserIdClaimType, user.Id),
new Claim(APIKeyConstants.ClaimTypes.Permission,
Permission.Create(Policies.Unrestricted).ToString())
};
return AuthenticateResult.Success(new AuthenticationTicket(
new ClaimsPrincipal(new ClaimsIdentity(claims, APIKeyConstants.AuthenticationType)),
APIKeyConstants.AuthenticationType));
}
}
}

View File

@ -1,15 +1,10 @@
using System;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using BTCPayServer.Client;
using BTCPayServer.Data;
using BTCPayServer.Security.Bitpay;
using BTCPayServer.Services.Stores;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Primitives;
@ -31,7 +26,7 @@ namespace BTCPayServer.Security.APIKeys
public static AuthenticationBuilder AddAPIKeyAuthentication(this AuthenticationBuilder builder)
{
builder.AddScheme<APIKeyAuthenticationOptions, APIKeyAuthenticationHandler>(AuthenticationSchemes.ApiKey,
builder.AddScheme<APIKeyAuthenticationOptions, APIKeyAuthenticationHandler>(AuthenticationSchemes.Greenfield,
o => { });
return builder;
}

View File

@ -4,6 +4,6 @@
{
public const string Cookie = "Identity.Application";
public const string Bitpay = "Bitpay";
public const string ApiKey = "GreenfieldApiKey";
public const string Greenfield = "Greenfield";
}
}

View File

@ -5,8 +5,7 @@
"description": "A full API to use your BTCPay Server",
"contact": {
"name": "BTCPay Server",
"url": "https://btcpayserver.org",
"email": "nicolas.dorier@gmail.com"
"url": "https://btcpayserver.org"
},
"version": "v1"
},
@ -105,7 +104,8 @@
{
"GreenField Authentication": [
"btcpay.user.canviewprofile"
]
],
"Basic": []
}
]
}
@ -182,7 +182,8 @@
{
"GreenField Authentication": [
"btcpay.server.cancreateuser"
]
],
"Basic": []
}
]
}
@ -347,9 +348,17 @@
"securitySchemes": {
"GreenField Authentication": {
"type": "apiKey",
"description": "BTCPay Server supports authenticating and authorizing users through an API Key that is generated by them. Send the API Key as a header value to Authorization with the format: token {token}. For a smoother experience, you can generate a url that redirects users to an API key creation screen.\n\n The following permissions applies to the context of the user creating the API Key:\n * `unrestricted`: Allow unrestricted access to your account.\n * `btcpay.server.canmodifyserversettings`: Allow total control on the server settings. (only if user is administrator)\n * `btcpay.server.cancreateuser`: Allow the creation new users on this server. (only if user is administrator)\n * `btcpay.user.canviewprofile`: Allow view access to your user profile.\n * `btcpay.user.canmodifyprofile`: Allow view and modification access to your user profile.\n\nThe following permissions applies to all stores of the user, you can limit to a specific store with the following format: `btcpay.store.cancreateinvoice:6HSHAEU4iYWtjxtyRs9KyPjM9GAQp8kw2T9VWbGG1FnZ`:\n * `btcpay.store.canviewstoresettings`: Allow view access to the stores settings. \n * `btcpay.store.canmodifystoresettings`: Allow view and modification access to the stores settings.\n * `btcpay.store.cancreateinvoice`: Allow invoice creation of the store.\n\nNote that API Keys only limits permission of a user and can never expand it. If an API Key has the permission `btcpay.server.canmodifyserversettings` but that the user account creating this API Key is not administrator, the API Key will not be able to modify the server settings.\n",
"description": "BTCPay Server supports authenticating and authorizing users through an API Key that is generated by them. Send the API Key as a header value to Authorization with the format: `token {token}`. For a smoother experience, you can generate a url that redirects users to an API key creation screen.\n\n The following permissions applies to the context of the user creating the API Key:\n * `unrestricted`: Allow unrestricted access to your account.\n * `btcpay.server.canmodifyserversettings`: Allow total control on the server settings. (only if user is administrator)\n * `btcpay.server.cancreateuser`: Allow the creation of new users on this server. (only if user is an administrator)\n * `btcpay.user.canviewprofile`: Allow view access to your user profile.\n * `btcpay.user.canmodifyprofile`: Allow view and modification access to your user profile.\n\nThe following permissions applies to all stores of the user, you can limit to a specific store with the following format: `btcpay.store.cancreateinvoice:6HSHAEU4iYWtjxtyRs9KyPjM9GAQp8kw2T9VWbGG1FnZ`:\n * `btcpay.store.canviewstoresettings`: Allow view access to the stores settings. \n * `btcpay.store.canmodifystoresettings`: Allow view and modification access to the stores settings.\n * `btcpay.store.cancreateinvoice`: Allow invoice creation of the store.\n\nNote that API Keys only limits permission of a user and can never expand it. If an API Key has the permission `btcpay.server.canmodifyserversettings` but that the user account creating this API Key is not administrator, the API Key will not be able to modify the server settings.\n",
"name": "Authorization",
"in": "header"
"in": "header",
"scheme": "token"
},
"Basic": {
"type": "http",
"description": "BTCPay Server supports authenticating and authorizing users through the Basic HTTP authentication scheme. Send the user and password encoded in base64 with the format `Basic {base64(username:password)}`. Using this authentication method implicitly provides you with the `unrestricted` permission",
"name": "Authorization",
"in": "header",
"scheme": "Basic"
}
}
},