Reputation: 2730
I have been asked to create a read-all policy for my API. Can I Create a filter of some kind that allows all HttpGet actions?
I have this polices that I apply manual on each controller/actions
public static void AddPolicies(this IServiceCollection services)
{
services.AddAuthorization(options =>
{
// APP_CE_READER
options.AddPolicy("Reader", policy =>
policy.RequireClaim("group", "89625d9c-6c0f-490e-8fe5-a06584b7a022"));
// APP_CE_EDIT_CUSTOMER
options.AddPolicy("EditCustomer", policy =>
policy.RequireClaim("group", "5f56395d-99d7-4f96-bc89-08e7c2206fc7"));
// APP_CE_EDIT_AGREEMENT
options.AddPolicy("EditAgreement", policy =>
policy.RequireClaim("group", "44cd2c55-9f78-440b-a77e-708e466433b4"));
});
}
Upvotes: 0
Views: 128
Reputation: 15005
The simplest way is to create a middleware and add it in the first of pipeline which reject all methods but get.
app.Use((context, next) =>
{
var options = context.RequestServices.GetService<IOptionsMonitor<ApiPolicyOptions>>();
if (options.CurrentValue.ReadOnly && !HttpMethods.IsGet(context.Request.Method))
{
context.Response.StatusCode = 500;
return context.Response.WriteAsync("Not allowed in read only mode");
}
else
{
return next();
}
});
public class ApiPolicyOptions
{
public bool ReadOnly { get; set; }
}
Upvotes: 1