![](/img/trans.png)
[英]JWT Auth works with Authorize Attribute but not with [Authorize (Policy = “Administrator”)]
[英]Add Requirements to Default [Authorize] policy
在 ASP.Net Core 中有可以添加到.AddAuthorization
的自定義策略。
但是,我需要向默認策略添加一個要求,因為它將在每個請求中使用。 有沒有一種方法可以做到這一點,而無需創建自定義策略並始終使用[Authorize("Policy")]
指定它?
services.AddAuthorization(options =>
{
options.AddPolicy("Unexpired",
policy => policy.Requirements.Add(new <requirement>));
...
有沒有辦法讓這個政策成為默認政策的一部分?
在 ASP.NET Core 5 中,它可能是您正在尋找的option
的DefaultPolicy
:
var unexpiredPolicy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser() // Remove if you don't need the user to be authenticated
.AddRequirements(new MyRequirement())
.Build();
services.AddSingleton<IAuthorizationHandler, MyRequirementHandler>();
services.AddAuthorization(options =>
{
// This line can be omitted if you don't need to be
// able to explicitly set the policy
options.AddPolicy("Unexpired", unexpiredPolicy);
// If no policy specified, use this
options.DefaultPolicy = unexpiredPolicy;
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.