簡體   English   中英

如何使用 OpenIddict 參數配置 SwaggerGen 以授予客戶端憑據?

[英]How do I configure SwaggerGen with OpenIddict parameters for 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)
    });
});

它顯示授權按鈕,但當我單擊它時,它會打開一個空模式,如下圖所示:

在此處輸入圖像描述

感謝任何可以向我指出一些文檔的人,這些文檔可以解釋我需要在services.AddSwaggerGen()中配置什么來進行配置,這樣我們就可以通過 Swagger 生成的交互式文檔輕松測試我們的 API。

在定義OpenApiSecurityScheme時,您需要指定更多選項。

您可以通過以下方式進行設置:

  • 指定TokenUrl 客戶端憑據流適用於/token端點,因此我們必須為其提供正確的 URL。 這里我使用了 IdentityServer 的演示服務器
  • 指定令牌將如何發送到后端:我們希望它在具有Bearer方案的Authorization標頭中發送。
  • 指定應用程序需要的范圍。 這是一個映射范圍 -> 描述的字典。
  • 最后,添加一個安全要求(這里是針對所有端點),它將在端點旁邊顯示一個鎖定圖標。 (這也有助於其他 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");
});

參考

您需要配置 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>()
                            }
                        }
                    );

});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM