[英]Add Requirements to Default [Authorize] policy
In ASP.Net Core there are custom policies that you can add to .AddAuthorization
.在 ASP.Net Core 中有可以添加到
.AddAuthorization
的自定义策略。
However, I need to add a requirement to the default policy because it will be used in every request.但是,我需要向默认策略添加一个要求,因为它将在每个请求中使用。 Is there a way I can do this without having to create a custom policy and always specifying it with
[Authorize("Policy")]
?有没有一种方法可以做到这一点,而无需创建自定义策略并始终使用
[Authorize("Policy")]
指定它?
services.AddAuthorization(options =>
{
options.AddPolicy("Unexpired",
policy => policy.Requirements.Add(new <requirement>));
...
Is there a way to make this policy part of the default?有没有办法让这个政策成为默认政策的一部分?
In ASP.NET Core 5, it's probably the option
's DefaultPolicy
you're looking for:在 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.