简体   繁体   English

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

[英]How do I configure SwaggerGen with OpenIddict parameters for client credentials grant?

I'm trying to figure out how I can configure SwaggerGen to populate/display the fields/parameters for OpenIddict and client credentials grant.我试图弄清楚如何配置 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)
    });
});

It's displaying the Authorize button but when I click it, it opens an empty modal like shown in the below image:它显示授权按钮,但当我单击它时,它会打开一个空模式,如下图所示:

在此处输入图像描述

Appreciate anyone who can point me at some docs that would explain what I need to configure in services.AddSwaggerGen() to get this configured so we can easily test our API through the interactive documentation generated by Swagger.感谢任何可以向我指出一些文档的人,这些文档可以解释我需要在services.AddSwaggerGen()中配置什么来进行配置,这样我们就可以通过 Swagger 生成的交互式文档轻松测试我们的 API。

You need to specify a couple more options when defining an OpenApiSecurityScheme .在定义OpenApiSecurityScheme时,您需要指定更多选项。

Here's how you can go about setting it up:您可以通过以下方式进行设置:

  • Specify TokenUrl .指定TokenUrl Client credentials flow works on /token endpoint, so we have to give it a correct URL.客户端凭据流适用于/token端点,因此我们必须为其提供正确的 URL。 Here I've used IdentityServer's demo server这里我使用了 IdentityServer 的演示服务器
  • Specify how the token will be sent to the backend: We want it to be sent in Authorization header with Bearer scheme.指定令牌将如何发送到后端:我们希望它在具有Bearer方案的Authorization标头中发送。
  • Specify which scopes the application needs.指定应用程序需要的范围。 This is a dictionary that maps scope -> description.这是一个映射范围 -> 描述的字典。
  • Finally, add a security requirement (here it's for all endpoints) that will show a lock icon next to the endpoint.最后,添加一个安全要求(这里是针对所有端点),它将在端点旁边显示一个锁定图标。 (That also helps other OpenAPI clients during code generation) (这也有助于其他 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" }
                    }
                }
            );
        }
    );
}

Here's how it looks when it's all set up:这是所有设置后的外观:

身份验证弹出

Once you authenticate, it gets filled with the token:身份验证后,它会填充令牌:

我们拿到了令牌

Now we can send requests, and Swagger UI includes the token in the headers as we'd expect:现在我们可以发送请求,Swagger UI 如我们所期望的那样在标头中包含令牌:

示例请求

Prefilling auth popup预填充身份验证弹出窗口

As a finishing touch, we can pre-populate the auth dialog with some default values:最后,我们可以使用一些默认值预填充 auth 对话框:

Inside the Startup:Configure methods where we set up the Swagger UI we can specify client id + secret (which defeats the purpose, but could prove useful in local development)在我们设置 Swagger UI 的Startup:Configure方法中,我们可以指定客户端 id + secret(这违背了目的,但在本地开发中可能会被证明是有用的)

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

Reference参考

You need to configure swagger to discover the OpenIddict configuration.您需要配置 swagger 来发现 OpenIddict 配置。 See code sample below:请参阅下面的代码示例:

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>()
                            }
                        }
                    );

});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 angular http 请求中实现 client_credentials 授权类型? - How to implement a client_credentials grant type in an angular http request? 如何使用 AD FS 2019 + MSAL 传递声明,使用 OAuth 2.0 客户端凭据授予类型 - How to pass though claims with AD FS 2019 + MSAL, using OAuth 2.0 client credentials grant type c#(rest服务)如何设置grant_type为key,value为client_credentials - How to set grant_type as key and value as client_credentials in c# (rest service) 在C#WebAPI中,如何配置CORS以允许具有凭据和JSON内容的POST请求? - In C# WebAPI, how do I configure CORS to allow a POST request with credentials and json content? 如何在 postman 中使用授权类型客户端凭据或谷歌驱动器密码获取访问令牌 - how to get access token using grant type client credentials or password for google drive in postman 如何使用参数配置mvc core 2依赖项注入,其中参数之一是依赖项? - How do I configure mvc core 2 dependency injection with parameters, where one of the parameters is a dependency? 使用openiddict时如何避免使用Microsoft的Microsoft.AspNet.Identity包 - How do I avoid using Microsofts's Microsoft.AspNet.Identity package when using openiddict .NET 核心配置 OpenIddict 与 MongoDb - .NET Core configure OpenIddict with MongoDb OpenIddict 密码授予返回状态码 415 - OpenIddict Password Grant returns Status Code 415 如何将用户名/密码凭据从php客户端传递到自托管的wcf服务? - How do I pass username/password credentials from php client to self-hosted wcf service?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM