If you have a minimal API you can either decorate your lambda for the .MapPost
app.MapGet("/weatherforecast2",
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
() =>
{
var forecast = Enumerable.Range(1, 5).Select(index =>
new WeatherForecast
(
DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
Random.Shared.Next(-20, 55),
summaries[Random.Shared.Next(summaries.Length)]
))
.ToArray();
return forecast;
})
.WithName("GetWeatherForecast2")
.WithOpenApi()
.RequireAuthorization("api");
if you have created the policy like this:
builder.Services.AddAuthorizationBuilder()
.AddPolicy("api", p => p.RequireRole("Role"));
then you can create the policy like this programmactly:
app.MapGet("/weatherforecast", () =>
{
var forecast = Enumerable.Range(1, 5).Select(index =>
new WeatherForecast
(
DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
Random.Shared.Next(-20, 55),
summaries[Random.Shared.Next(summaries.Length)]
))
.ToArray();
return forecast;
})
.WithName("GetWeatherForecast")
.WithOpenApi()
.RequireAuthorization(auth =>
{
auth.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme);
auth.RequireRole("Role");
});
only thing to remember is that you cannot refer to your added policies in the builder.Services.AddAuthorizationBuilder command
PS. For future googlers, is it possible to refer a the created policy named "api" when doing the RequireAuthorization with lambda config?