为什么 dotnet 核心 [授权] 在设置默认值时需要方案



我已经使用 dotnet core 2.0 设置了身份验证,如下所示:

1( 在启动时Configure(..)中添加app.UseAuthentication();.cs

2( 添加到ConfigureServices(..)启动.cs

services.AddAuthentication(options =>
{
    options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = GoogleDefaults.AuthenticationScheme;
})
.AddCookie()
.AddGoogle(options =>
{
    options.ClientId = Configuration["auth:google:clientid"];
    options.ClientSecret = Configuration["auth:google:clientsecret"];
});

如果我在我的 web-api 控制器上放置一个 [Authorize] 属性,它将挑战我谷歌,我选择一个帐户,它会永远循环。

我发现的修复程序(.net core 2 Google身份验证登录循环(是指定一个身份验证方案,如下所示:

[Authorize(AuthenticationSchemes = GoogleDefaults.AuthenticationScheme)][Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme)]

(奇怪的是:to-me:在这种情况下两者都有效(

但是,当我指定默认方案时,我不确定为什么需要它。

如果默认方案不相关,我可以指定默认方案吗,因为我不想每次使用该属性时都必须指定它。

只需添加这个,它将授权所有控制器/方法,除了那些带有 [允许匿名] 的控制器/方法:

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

最新更新