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

uqjltbpv  于 2022-11-06  发布在  其他
关注(0)|答案(2)|浏览(265)

我正在尝试弄清楚如何配置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)
    });
});

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

感谢任何人谁可以告诉我一些文档,将解释我需要配置在services.AddSwaggerGen()得到这个配置,使我们可以很容易地测试我们的API通过交互式文档生成的Swagger。

3bygqnnd

3bygqnnd1#

在定义OpenApiSecurityScheme时,您需要指定多个选项。
以下是您可以进行设置的方法:

  • 指定TokenUrl。客户端凭据流在/token端点上工作,因此我们必须为其给予一个正确的URL。
  • 指定将令牌发送到后端的方式:我们希望使用Bearer方案在Authorization标头中发送它。
  • 指定应用程序需要的作用域。这是一个Map作用域-〉描述的字典。
  • 最后,添加一个安全需求(这里是针对所有端点的),在端点旁边显示一个锁图标。(这也有助于其他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" }
                    }
                }
            );
        }
    );
}

以下是设置完成后的外观:

进行身份验证后,它将被令牌填充:

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

预填充身份验证弹出窗口

最后,我们可以在auth对话框中预填充一些默认值:
在设置Swagger UI的Startup:Configure方法中,我们可以指定客户端id + secret(这与目的不符,但在本地开发中可能会证明有用)

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

参考

  • https://github.com/domaindrivendev/Swashbuckle.AspNetCore#add-security-definitions-and-requirements
1tu0hz3e

1tu0hz3e2#

您需要配置swagger来发现OpenIddict配置。请参见下面的代码示例:

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 = HeaderNames.Authorization,
        Flows = new OpenApiOAuthFlows
        {
            ClientCredentials = new OpenApiOAuthFlow
            {
                AuthorizationUrl = new Uri("/connect/token", UriKind.Relative), 
                TokenUrl = new Uri("/connect/token", UriKind.Relative)
            }
        },
        OpenIdConnectUrl = new Uri("/.well-known/openid-configuration", UriKind.Relative)
    });

    options.AddSecurityRequirement(
                        new OpenApiSecurityRequirement
                        {
                            {
                                new OpenApiSecurityScheme
                                {
                                    Reference = new OpenApiReference
                                        { Type = ReferenceType.SecurityScheme, Id = "oauth" },
                                },
                                Array.Empty<string>()
                            }
                        }
                    );

});

相关问题