Swashbuckle Swagger UI OpenID Connect 支持

Ale*_*res 6 swagger-ui openid-connect swashbuckle asp.net-core-webapi

根据https://swagger.io/docs/specification/authentication/openid-connect-discovery/,Swagger UI 现在支持 OpenID Connect。有谁知道或有一个示例项目来解释如何使用 Swashbuckle 或 NSwag 使用 OpenID Connect 配置 Asp.net Core Web API 项目?

Bra*_*ang 10

据我所知,如果你想在 swagger UI 中使用 OpenID Connect,你应该安装 Swagger UI 捆绑到 v.3.38.0 以后版本的 Swashbuckle。

然后你可以像下面这样使用它:

services.AddSwaggerGen(options =>
{
    var apiinfo = new OpenApiInfo
    {
        Title = "theta-CandidateAPI",
        Version = "v1",
        Description = "Candidate API for thetalentbot",
        Contact = new OpenApiContact
        { Name = "thetalentbot", Url = new Uri("https://thetalentbot.com/developers/contact") },
            License = new OpenApiLicense()
            {
                Name = "Commercial",
                Url = new Uri("https://thetalentbot.com/developers/license")
             }
        };

        OpenApiSecurityScheme securityDefinition = new OpenApiSecurityScheme()
        {
            Name = "Bearer",
            BearerFormat = "JWT",
            Scheme = "bearer",
            Description = "Specify the authorization token.",
            In = ParameterLocation.Header,
            Type = SecuritySchemeType.Http,
        };

        OpenApiSecurityRequirement securityRequirements = new OpenApiSecurityRequirement()
        {
            {securityScheme, new string[] { }},
        };

        options.SwaggerDoc("v1", apiinfo);
        options.AddSecurityDefinition("jwt_auth", securityDefinition);
        // Make sure swagger UI requires a Bearer token to be specified
        options.AddSecurityRequirement(securityRequirements);               
});
Run Code Online (Sandbox Code Playgroud)

如果您想使用 OpenID Connect Discovery,您可以在其中添加以下代码。

services.AddSwaggerGen(c =>
{
    //... omitted for brevity
    //baseAccountsUrl is "https://localhost:5401"

    c.AddSecurityDefinition("AccountsOpenID", new OpenApiSecurityScheme
    {
        Type = SecuritySchemeType.OpenIdConnect,
        OpenIdConnectUrl = new Uri($"{baseAccountsUrl}/.well-known/openid-configuration")
    });
}
Run Code Online (Sandbox Code Playgroud)