0

I need to authenticate Swagger UI against Azure Identity Provider. I need to implement a ClientCredential flow. The authentication works if I use Postman, so the Azure Identity Provider is well configured!

Here the code I am using to authenticate SwaggerUI:

In the Program.cs:

builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new OpenApiInfo { Title = "...", Version = "v1" });
                
    c.AddSecurityDefinition("aad-jwt", new OpenApiSecurityScheme
    {
        Type = SecuritySchemeType.OAuth2,
        Flows = new OpenApiOAuthFlows()
        { 
            ClientCredentials = new OpenApiOAuthFlow()
            { 
                TokenUrl = new Uri($"https://login.microsoftonline.com/{tenantId}/oauth2/v2.0/token"),
                Scopes =  new Dictionary<string, string> { { scope, "Access web api" } }
            }
        }
    });
                
    c.AddSecurityRequirement(new OpenApiSecurityRequirement() {
        {
            new OpenApiSecurityScheme {
                Reference = new OpenApiReference {
                    Type = ReferenceType.SecurityScheme,
                    Id = "aad-jwt"
                },
                UnresolvedReference = true
            },
            new List<string>()
        }
    });
});      

builder.Services.AddCors(options =>
{
    options.AddPolicy("allowany",
        policy =>
        {
            policy.WithHeaders(
                //Microsoft minimum set recommended 
                "Accept", "Content-Type", "Origin"
                //Swagger headers
                "api_key", "authorization", "x-requested-with")
            .AllowAnyOrigin();
        });
});     

Then:

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI(c =>
    {
        c.OAuthClientId("...");
        c.OAuthClientSecret("...");
        c.OAuthUseBasicAuthenticationWithAccessCodeGrant();
   
    }).UseCors("allowany");
}

I have copied the cors part from here: How to setup ClientCredentials flow with swagger UI and workaround options preflight issue (CORS)

I have also found this question:

https://learn.microsoft.com/en-us/answers/questions/353629/cors-issue-while-getting-token-with-oauth-2-0-clie

It is written that in Client Credential Flow the Origin header should not be present. But I do not understand how to remove it from SwaggerUI.

Any help please?

Thank you

Simone
  • 2,304
  • 6
  • 30
  • 79

0 Answers0