I was following: https://www.youtube.com/watch?v=r7gEKqSlb40 and got all the app registrations working. After I log in via Swagger, it seems that swagger is not passing on the authorization to the controller.
This is the piece of code:
{
config.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo { Title = "Test", Version = "V1" });
config.AddSecurityDefinition("OAuth2", new Microsoft.OpenApi.Models.OpenApiSecurityScheme
{
Description = "OAuth2 which uses authorization flow",
Name = "OAuth2",
Type = SecuritySchemeType.OAuth2,
Flows = new OpenApiOAuthFlows
{
AuthorizationCode = new OpenApiOAuthFlow
{
AuthorizationUrl = new Uri(builder.Configuration["SwaggerAzureAD:AuthorozationUrl"]),
TokenUrl = new Uri(builder.Configuration["SwaggerAzureAD:TokenUrl"]),
Scopes = new Dictionary<string, string>
{
{builder.Configuration["SwaggerAzureAD:Scope"], "Access API as user" }
}
}
}
});
config.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference{Type=ReferenceType.SecurityScheme, Id = "oauth2"}
},
new [] {builder.Configuration["SwaggerAzureAD:Scope"]}
}
});
});
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.OAuthClientId(builder.Configuration["SwaggerAzureAD:ClientId"]);
c.OAuthUsePkce();
c.OAuthScopeSeparator(" ");
});
}
but my endpoint seems to think it is not needed:
any clue what I am doing wrong?
this is my code in controller: standard generated:
namespace WebApplication2.Controllers
{
[RequiredScope(RequiredScopesConfigurationKey = "AzureAd:Scopes")]
[Authorize]
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
[HttpGet(Name = "GetWeatherForecast")]
public IEnumerable<WeatherForecast> Get()
{
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
}
}
}
and like always, it was a really stupid typo.
in this piece:
config.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference{Type=ReferenceType.SecurityScheme, Id = "oauth2"}
},
new [] {builder.Configuration["SwaggerAzureAD:Scope"]}
}
});
the Id was wrong and needs to be: OAuth2
Then it is being picked up.