Reputation: 4727
I am working in .NET 5 Web API with Azure AD Authentication. One of my Controller is protected with [Authorize]. When trying to call those API from Swagger I was getting Unauthorized Error.
So in my startup I have configured like this
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "MyProject", Version = "v1.0.0" });
c.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
{
Type = SecuritySchemeType.OAuth2,
Flows = new OpenApiOAuthFlows()
{
Implicit = new OpenApiOAuthFlow()
{
AuthorizationUrl = new Uri($"https://login.microsoftonline.com/{Configuration["TenantId"]}/oauth2/v2.0/authorize"),
TokenUrl = new Uri($"https://login.microsoftonline.com/{Configuration["TenantId"]}/oauth2/v2.0/token")
}
}
});
});
So it shown an Authorize button on Top and on clicking on that prompts me to specify client id
I specified the client id and clicked on Authorize. But its saying the request must contain Scope parameter
I have not idea how to deal with it or not sure this is the correct way to Authorize swagger. Please share your suggestion. I am pretty new to Swagger
Also its asking me for Client ID. But is there is anyway (If I following the correct way) to specify the clientid in code so no need to specify it when prompt?
Upvotes: 0
Views: 884
Reputation: 39
you should add AddSecurityRequirement
c.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme, // or ReferenceType.Parameter
Id = "oauth2"
}
},
new string[] {}
}
});
Upvotes: 1