如何使用 OpenIddict 参数配置 SwaggerGen 以获取客户端凭据授予?

tnk*_*479 5 c# asp.net-web-api swagger asp.net-core openiddict

我试图弄清楚如何配置 SwaggerGen 来填充/显示 OpenIddict 和客户端凭据授予的字段/参数。

services.AddDbContext<AppDbContext>(options =>
{
    options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
    options.UseOpenIddict();
});

services.AddOpenIddict()
    .AddCore(options =>
    {
        // Configure OpenIddict to use the Entity Framework Core stores and models.
        // Note: call ReplaceDefaultEntities() to replace the default entities.
        options.UseEntityFrameworkCore().UseDbContext<AppDbContext>();
    })
    .AddServer(options =>
    {
        // Enable the token endpoint.
        options.SetTokenEndpointUris("/connect/token");

        // Enable the client credentials flow.
        options.AllowClientCredentialsFlow();

        // Register the signing and encryption credentials.
        options.AddDevelopmentEncryptionCertificate()
              .AddDevelopmentSigningCertificate();

        // Register the ASP.NET Core host and configure the ASP.NET Core options.
        options.UseAspNetCore()
              .EnableTokenEndpointPassthrough();
    })
    .AddValidation(options =>
    {
        // Import the configuration from the local OpenIddict server instance.
        options.UseLocalServer();

        // Register the ASP.NET Core host.
        options.UseAspNetCore();
    });

services.AddSwaggerGen(options =>
{
    options.SwaggerDoc("v1", new OpenApiInfo { Title = "PCM", Version = "v1" });
    options.AddSecurityDefinition("Authentication", new OpenApiSecurityScheme
    {
        Type = SecuritySchemeType.OpenIdConnect,
        Description = "Description", 
        In = ParameterLocation.Header, 
        Name = "Notsure", 
        Flows = new OpenApiOAuthFlows
        {
            ClientCredentials = new OpenApiOAuthFlow
            {
                AuthorizationUrl = new Uri("/connect/token", UriKind.Relative), 
                TokenUrl = new Uri("/connect/token", UriKind.Relative), 
                Scopes = new Dictionary<string, string>()
                {

                }
            }
        },
        OpenIdConnectUrl = new Uri("/connect/authorize", UriKind.Relative)
    });
});
Run Code Online (Sandbox Code Playgroud)

它显示“授权”按钮,但当我单击它时,它会打开一个空模式,如下图所示:

在此输入图像描述

感谢任何可以向我指出一些文档的人,这些文档将解释我需要配置什么才能services.AddSwaggerGen()进行配置,以便我们可以通过 Swagger 生成的交互式文档轻松测试我们的 API。

abd*_*sco 8

定义OpenApiSecurityScheme.

您可以按照以下步骤进行设置:

  • 指定TokenUrl。客户端凭证流在/token端点上运行,因此我们必须为其提供正确的 URL。这里我使用了IdentityServer的演示服务器
  • Authorization指定令牌如何发送到后端:我们希望它通过方案在标头中发送Bearer
  • 指定应用程序需要哪些范围。这是一个映射范围 -> 描述的字典。
  • 最后,添加安全要求(此处适用于所有端点),该要求将在端点旁边显示一个锁图标。(这也有助于代码生成期间的其他 OpenAPI 客户端)
public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();
    services.AddSwaggerGen(
        c =>
        {
            c.SwaggerDoc("v1", new OpenApiInfo { Title = "ApiPlayground", Version = "v1" });
            c.AddSecurityDefinition(
                "oauth",
                new OpenApiSecurityScheme
                {
                    Flows = new OpenApiOAuthFlows
                    {
                        ClientCredentials = new OpenApiOAuthFlow
                        {
                            Scopes = new Dictionary<string, string>
                            {
                                ["api"] = "api scope description"
                            },
                            TokenUrl = new Uri("https://demo.identityserver.io/connect/token"),
                        },
                    },
                    In = ParameterLocation.Header,
                    Name = HeaderNames.Authorization,
                    Type = SecuritySchemeType.OAuth2
                }
            );
            c.AddSecurityRequirement(
                new OpenApiSecurityRequirement
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference
                                { Type = ReferenceType.SecurityScheme, Id = "oauth" },
                        },
                        new[] { "api" }
                    }
                }
            );
        }
    );
}
Run Code Online (Sandbox Code Playgroud)

全部设置完毕后的外观如下:

授权弹出窗口

一旦您进行身份验证,它就会填充令牌:

我们得到了令牌

现在我们可以发送请求,并且 Swagger UI 正如我们所期望的那样在标头中包含令牌:

示例请求

预填充身份验证弹出窗口

作为最后的修饰,我们可以使用一些默认值预先填充身份验证对话框:

Startup:Configure我们设置 Swagger UI 的方法中,我们可以指定客户端 id + 密钥(这违背了目的,但在本地开发中可能有用)

app.UseSwaggerUI(c => {
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "ApiPlayground v1");
    c.OAuthClientId("m2m");
    c.OAuthClientSecret("secret");
});
Run Code Online (Sandbox Code Playgroud)

参考