为什么自定义策略中允许未经身份验证的请求? [英] Why are unauthenticated requests allowed in custom policies?

查看:57
本文介绍了为什么自定义策略中允许未经身份验证的请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用具有以下设置的Cookie身份验证:

I'm using cookie auth with the following settings:

app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationScheme = CookieAuthenticationDefaults.AuthenticationScheme,
            AutomaticAuthenticate = true,
            AutomaticChallenge = false,
            ExpireTimeSpan = new TimeSpan(2, 0, 0)
        });

我假设将 [Authorize] 属性与声明的策略一起使用需要在评估自定义要求之前对用户进行身份验证,但是事实并非如此.

I've assumed that using the [Authorize] attribute with a policy declared requires a user to be authenticated before evaluating custom requirements, however, it's not the case.

也尝试过此操作(请注意对 RequireAuthenticatedUser()的调用):

This has also been attempted (note the call to RequireAuthenticatedUser()):

options.AddPolicy("MyPolicy",
                policy =>
                {
                    policy.RequireAuthenticatedUser();
                    policy.Requirements.Add(
                        new SomeRequirement(serviceProvider.GetService<IMyService>()));
                });

但是,即使那样,在我的 SomeRequirement AuthorizationHandler 中,仍会执行 HandleRequirementAsync().为什么?

However, even then, in my AuthorizationHandler for SomeRequirement, HandleRequirementAsync() still gets executed. Why?

我真的真的真的不想检查用户是否在每个 AuthenticationHandler 中都经过了验证,如下所示:

I really, really, really don't want to check if user is authenticated in every AuthenticationHandler like this:

if (!context.User.Identity.IsAuthenticated)
{
    context.Fail();
    return Task.CompletedTask;
}

推荐答案

不想在您的自定义策略中处理未经身份验证的请求?请执行 blowdart 在GitHub上的ASP.NET授权研讨会中列出的内容:

Don't want to deal with unauthenticated requests in your custom policies? Do what's listed in blowdart's ASP.NET Authorization Workshop on GitHub: authorize all endpoints with a default policy.

services.AddMvc(config =>
{
    var policy = new AuthorizationPolicyBuilder()
                 .RequireAuthenticatedUser()
                 .Build();
    config.Filters.Add(new AuthorizeFilter(policy));
});

然后在需要的地方使用 [AllowAnonymous] .

Then use [AllowAnonymous] where needed.

这篇关于为什么自定义策略中允许未经身份验证的请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆