Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't authorize swagger through my Authorization Server using OIDC

I'm using Swashbuckle configured as

services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v2", new OpenApiInfo { Title = "API", Version = "v2" });
    c.AddSecurityDefinition("OpenId", new OpenApiSecurityScheme
    {
        Type = SecuritySchemeType.OpenIdConnect,
        Name = "Authorization",
        In = ParameterLocation.Header,
        Scheme = "Bearer",
        Flows = new OpenApiOAuthFlows
        {
            AuthorizationCode = new OpenApiOAuthFlow
            {
                AuthorizationUrl = new Uri($"{authority}connect/authorize"),
                TokenUrl = new Uri($"{authority}connect/token"),
                Scopes = new Dictionary<string, string>
                {
                    {
                        "openid", "openid"
                    },
                    {
                        "api", "api"
                    },
                },
            },
        },
        OpenIdConnectUrl = new Uri($"{authority}.well-known/openid-configuration"),
    });

    c.AddSecurityRequirement(new OpenApiSecurityRequirement
    {
        {
            new OpenApiSecurityScheme
            {
                Reference = new OpenApiReference
                {
                    Type = ReferenceType.SecurityScheme,
                    Id = "OpenId",
                },
            },
            new List<string> { "api", "openid" }
        },
    });
});

And after that

app.UseSwagger();
app.UseSwaggerUI(c =>
{
    c.SwaggerEndpoint("/swagger/v2/swagger.json", "API v2");
    c.OAuthUsePkce();
    c.OAuthClientId(Configuration.GetRequiredSection("SwaggerOptions:ClientId").Value);
    c.OAuthClientSecret(Configuration.GetRequiredSection("SwaggerOptions:ClientSecret").Value);
    c.EnablePersistAuthorization();
    c.OAuthScopes("api", "openid");
});

I see resulting swagger.json seems to be correct, as it declared at the docs

enter image description here

But something goes definitely wrong - I get CORS header 'Access-Control-Allow-Origin' missing reason for discovery request rejecting, simultaneously it returns a correct configuration with 200 ok

enter image description here

What have I missed?

like image 366
anatol Avatar asked Sep 05 '25 03:09

anatol


1 Answers

Eventually, I was able to get this to work. I was misunderstanding which part does require CORS in this case. To fix that, I added my Swagger UI host to allowed hosts on auth server side and switch CORS on there. Now, all work fine!

like image 181
anatol Avatar answered Sep 09 '25 02:09

anatol