【问题标题】:Cookie Authentication not working with Authorization policy in asp.net coreCookie 身份验证不适用于 asp.net 核心中的授权策略
【发布时间】:2018-02-20 21:50:10
【问题描述】:

将 Scott Wildermuth 的 World Trip 应用程序升级到 ASP.NET Core 2.0。下面的代码不起作用。

由于我使用两种身份验证类型并且我希望两者都在 api 控制器上工作,因此我决定使用授权策略。

public void ConfigureServices(IServiceCollection services)
{
   //Some code here
   services.AddAuthentication()
       .AddCookie()
       .AddJwtBearer(/*Implementation is fine*/);

   services.AddAuthorization(options =>
   {
       options.AddPolicy("Authenticated", policy =>
       {
           policy.AddAuthenticationSchemes(
               CookieAuthenticationDefaults.AuthenticationScheme,
               JwtBearerDefaults.AuthenticationScheme)
                   .RequireAuthenticatedUser();
       });
   });
}

现在在我的控制器中,

namespace TheWorld.Controllers.Api
{
    [Route("api/trips")]
    [Authorize(policy: "Authenticated")]
    public class TripsController : controller
    {
      // Implementation is fine
    }
}

来自具有 cookie 身份验证的客户端(Web)的请求永远不会被视为已通过身份验证,而来自 Jwt 身份验证客户端的请求按预期工作。

如果我在控制器上使用简单的[Authorize],它只适用于 cookie 身份验证,其中 asp.net 核心只选择默认的 cookie 身份验证,并且从不接受来自 Jwt 客户端的请求。

【问题讨论】:

    标签: c# asp.net-mvc authentication cookies asp.net-core


    【解决方案1】:
    policy.AddAuthenticationSchemes(scheme1, scheme2)
    

    这意味着要使策略身份验证成功,两个指定的身份验证方案都必须成功。

    您的两个身份验证方案可能设置为当 JWT 身份验证成功时,它会自动成功 cookie 身份验证(在这种情况下设置 cookie,因此进一步请求不再需要 JWT 令牌,但 cookie 是足够的)。所以当JWT认证成功时,cookie认证也成功了。但是,反之则不然:如果您只是使用 cookie 来建立身份验证,那么 JWT 令牌可能根本不存在。

    如果您不关心 哪个 身份验证方案提供了身份验证,则应该删除 AddAuthenticationSchemes 调用。通过说policy.RequireAuthenticatedUser(),您基本上是在说需要一些身份验证方案来成功验证用户身份。

    这是顺便说一句。完全相同的行为,默认策略(只有[Authorize])具有。

    【讨论】:

    • 谢谢@poke。我已经尝试过您提到的内容,在这种情况下发生的情况是 CookieAuthentication 被选为默认值,而 JwtBearer 从未使用过。谢谢。
    • 谢谢@poke。我终于发现问题出在AspNetCore.Identity。附带的默认AuthenticationScheme 使用方案名称"Identity.Application"。因此,在我将CookieAuthenticationDefaults.AuthenticationScheme 更改为"Identity.Application" 后,应用程序工作正常,无论是否在services.AddAuthentication 上调用.AddCookie
    • 感谢@MubarakImam,这两个方案都对我有用。 [Authorize(AuthenticationSchemes = "Identity.Application" + "," + JwtBearerDefaults.AuthenticationScheme)]
    猜你喜欢
    • 2021-06-26
    • 1970-01-01
    • 2019-10-21
    • 1970-01-01
    • 2020-09-10
    • 2016-05-29
    • 2017-05-11
    • 1970-01-01
    • 2019-06-12
    相关资源
    最近更新 更多