Alexander Torres
Alexander Torres

Reputation: 69

Swashbuckle Swagger UI OpenID Connect Support

According to https://swagger.io/docs/specification/authentication/openid-connect-discovery/, Swagger UI now has support for OpenID Connect. Does anyone know or have a sample project that explains how to configure an Asp.net Core Web API project using Swashbuckle or NSwag using OpenID Connect?

Upvotes: 6

Views: 9424

Answers (1)

Brando Zhang
Brando Zhang

Reputation: 27962

As far as I know, if you want to use the OpenID Connect in swagger UI, you should install the Swashbuckle which is bundled Swagger UI to the v. 3.38.0 later version.

Then I you could use it like below:

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

If you want to use OpenID Connect Discovery, you could add below codes in it,.

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

Upvotes: 10

Related Questions