[Authorize(Policy =“PolicyName”)]在asp.net core中如何工作?

ttygqcqt  于 2023-08-08  发布在  .NET
关注(0)|答案(2)|浏览(115)

谁能告诉我[Authorize(Policy =“PolicyName”)]是如何工作的,当用户未登录时,为什么策略会运行?例如,如果我从.RequireAssertion方法的委托返回'true',即使用户是匿名用户,操作或控制器也是可访问的?

[Authorize]
[Authorize(Policy = "TestAccess")]
public async Task<IActionResult> Test()
{
   return Json("Test Actioned Reached");
}

字符串
为什么这里需要[Authorize]属性?如果[Authorize(Policy =“TestAccess”)]表示当用户不是匿名用户且此策略被传递时,将访问- action/controller?
如果我写:

[Authorize(Policy = "TestAccess")]
public async Task<IActionResult> Test()
{
    return Json("Test Actioned Reached");
}


政策是这样的:

services.AddAuthorization(options => {
options.AddPolicy("TestAccess", policy => policy.RequireAssertion(context =>
   {
       return true;  // For Testing only

   }));
});


即使用户是匿名用户,也会执行Test()操作。这是怎么回事对不起,我的英语不好。- 谢谢-谢谢

wz3gfoph

wz3gfoph1#

在下面的代码中尝试

services.AddAuthorization(options => {
                    options.AddPolicy("TestAccess", policy => policy.RequireAssertion(context => context.User.HasClaim("your claim type ","your claim value")));
                });

字符串
你的代码只是简单地在需求管道中添加true

services.AddAuthorization(options => {
options.AddPolicy("TestAccess", policy => policy.RequireAssertion(context =>
   {
       return true;  // For Testing only

   }));
});


上面的代码在处理程序的管道中添加true,并且true满足所有条件,包括匿名用户。
更多细节请看方法src代码

public AuthorizationPolicyBuilder RequireAssertion(Func<AuthorizationHandlerContext, bool> handler)
        {
            if (handler == null)
            {
                throw new ArgumentNullException(nameof(handler));
            }

            Requirements.Add(new AssertionRequirement(handler));
            return this;
        }


AuthorizationPolicyBuilder.cs

9gm1akwq

9gm1akwq2#

policy.RequireAthenticatedUser();

字符串

相关问题