Add Swagger and Redoc

Blocked by #1262
This commit is contained in:
Kukks 2020-02-18 10:50:01 +01:00
parent 276a9a95f9
commit 023e64704d
6 changed files with 122 additions and 3 deletions

View File

@ -48,6 +48,7 @@
<PackageReference Include="NicolasDorier.CommandLine.Configuration" Version="1.0.0.3" />
<PackageReference Include="NicolasDorier.RateLimits" Version="1.1.0" />
<PackageReference Include="NicolasDorier.StandardConfiguration" Version="1.0.0.18" />
<PackageReference Include="NSwag.AspNetCore" Version="13.2.2" />
<PackageReference Include="Serilog" Version="2.9.0" />
<PackageReference Include="Serilog.AspNetCore" Version="3.2.0" />
<PackageReference Include="Serilog.Sinks.File" Version="4.1.0" />

View File

@ -4,13 +4,16 @@ using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using BTCPayServer.Data;
using BTCPayServer.Hosting.OpenApi;
using BTCPayServer.Models;
using BTCPayServer.Security;
using BTCPayServer.Security.APIKeys;
using ExchangeSharp;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using NSwag.Annotations;
namespace BTCPayServer.Controllers
{
@ -56,8 +59,16 @@ namespace BTCPayServer.Controllers
return View("AddApiKey", await SetViewModelValues(new AddApiKeyViewModel()));
}
/// <param name="permissions">The permissions to request. Current permissions available: ServerManagement, StoreManagement</param>
/// <param name="applicationName">The name of your application</param>
/// <param name="strict">If permissions are specified, and strict is set to false, it will allow the user to reject some of permissions the application is requesting.</param>
/// <param name="selectiveStores">If the application is requesting the CanModifyStoreSettings permission and selectiveStores is set to true, this allows the user to only grant permissions to selected stores under the user's control.</param>
[HttpGet("~/api-keys/authorize")]
public async Task<IActionResult> AuthorizeAPIKey( string[] permissions, string applicationName = null,
[OpenApiTags("Authorization")]
[OpenApiOperation("Authorize User",
"Redirect the browser to this endpoint to request the user to generate an api-key with specific permissions")]
[IncludeInOpenApiDocs]
public async Task<IActionResult> AuthorizeAPIKey(string[] permissions, string applicationName = null,
bool strict = true, bool selectiveStores = false)
{
if (!_btcPayServerEnvironment.IsSecure)

View File

@ -142,7 +142,7 @@ namespace BTCPayServer.Controllers
[HttpPost]
[Route("{storeId}/derivations/{cryptoCode}")]
public async Task<IActionResult> AddDerivationScheme(string storeId, DerivationSchemeViewModel vm,
public async Task<IActionResult> AddDerivationScheme(string storeId, [FromBody] DerivationSchemeViewModel vm,
string cryptoCode)
{
vm.CryptoCode = cryptoCode;

View File

@ -26,6 +26,7 @@ using System.Threading;
using BTCPayServer.Services.Wallets;
using BTCPayServer.Logging;
using BTCPayServer.HostedServices;
using BTCPayServer.Hosting.OpenApi;
using BTCPayServer.PaymentRequest;
using BTCPayServer.Payments;
using BTCPayServer.Payments.Bitcoin;
@ -262,7 +263,7 @@ namespace BTCPayServer.Hosting
}
return rateLimits;
});
services.AddBTCPayOpenApi();
services.AddLogging(logBuilder =>
{
@ -291,6 +292,7 @@ namespace BTCPayServer.Hosting
public static IApplicationBuilder UsePayServer(this IApplicationBuilder app)
{
app.UseMiddleware<BTCPayMiddleware>();
app.UseBTCPayOpenApi();
return app;
}
public static IApplicationBuilder UseHeadersOverride(this IApplicationBuilder app)

View File

@ -0,0 +1,9 @@
using System;
namespace BTCPayServer.Hosting.OpenApi
{
public class IncludeInOpenApiDocs : Attribute
{
}
}

View File

@ -0,0 +1,96 @@
using System;
using System.Collections.Generic;
using System.Linq;
using BTCPayServer.Payments;
using BTCPayServer.Security;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using NJsonSchema;
using NJsonSchema.Generation.TypeMappers;
using NSwag;
using NSwag.Generation.Processors.Security;
namespace BTCPayServer.Hosting.OpenApi
{
public static class OpenApiExtensions
{
public static IServiceCollection AddBTCPayOpenApi(this IServiceCollection serviceCollection)
{
return serviceCollection.AddOpenApiDocument(config =>
{
config.PostProcess = document =>
{
document.Info.Version = "v1";
document.Info.Title = "BTCPay Greenfield API";
document.Info.Description = "A full API to use your BTCPay Server";
document.Info.TermsOfService = null;
document.Info.Contact = new NSwag.OpenApiContact
{
Name = "BTCPay Server", Email = string.Empty, Url = "https://btcpayserver.org"
};
};
config.AddOperationFilter(context =>
{
var methodInfo = context.MethodInfo;
if (methodInfo != null)
{
return methodInfo.CustomAttributes.Any(data =>
data.AttributeType == typeof(IncludeInOpenApiDocs)) ||
methodInfo.DeclaringType.CustomAttributes.Any(data =>
data.AttributeType == typeof(IncludeInOpenApiDocs));
}
return false;
});
config.AddSecurity("APIKey", Enumerable.Empty<string>(),
new OpenApiSecurityScheme
{
Type = OpenApiSecuritySchemeType.ApiKey,
Name = "Authorization",
In = OpenApiSecurityApiKeyLocation.Header,
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."
});
config.OperationProcessors.Add(
new BTCPayPolicyOperationProcessor("APIKey", AuthenticationSchemes.ApiKey));
config.TypeMappers.Add(
new PrimitiveTypeMapper(typeof(PaymentType), s => s.Type = JsonObjectType.String));
config.TypeMappers.Add(new PrimitiveTypeMapper(typeof(PaymentMethodId),
s => s.Type = JsonObjectType.String));
});
}
public static IApplicationBuilder UseBTCPayOpenApi(this IApplicationBuilder builder)
{
return builder.UseOpenApi()
.UseReDoc(settings => settings.Path = "/docs");
}
class BTCPayPolicyOperationProcessor : AspNetCoreOperationSecurityScopeProcessor
{
private readonly string _authScheme;
public BTCPayPolicyOperationProcessor(string x, string authScheme) : base(x)
{
_authScheme = authScheme;
}
protected override IEnumerable<string> GetScopes(IEnumerable<AuthorizeAttribute> authorizeAttributes)
{
var result = authorizeAttributes
.Where(attribute => attribute?.AuthenticationSchemes != null && attribute.Policy != null &&
attribute.AuthenticationSchemes.Equals(_authScheme,
StringComparison.InvariantCultureIgnoreCase))
.Select(attribute => attribute.Policy);
return result;
}
}
}
}