【问题标题】:Cookie authorization works only for Scaffolded Identity AreaCookie 授权仅适用于脚手架身份区域
【发布时间】:2022-01-03 21:48:16
【问题描述】:

我正在开发一个使用 IdentityServer 进行身份验证的项目。后端应用包括:

  • 很少有用于管理相关任务的 Razor 页面。用户应该获得 cookie 授权。
  • 移动应用程序。用户应该获得 JWT 令牌的授权。

只要我尝试从 Identity/Pages/Account/* 区域(如屏幕截图所示)访问脚手架页面,如 Login.cshtml 或 Register.cshtml,身份 cookie 就可以正确使用并且我能够查看用户声明并使用 [Authorize] 属性没有任何问题。

但是在 Pages/Admin 路径中创建新的 Razor 页面集后,我注意到没有使用 cookie,即使它在请求中提供。我认为这是因为默认情况下,IdentityServerJwt 方案用于授权。

我设法通过为我新创建的页面指定以下属性来实现此功能:

[Authorize(AuthenticationSchemes = "Identity.Application")]

然后正确地使用 cookie 来授权用户,但这并不理想,因为我无法读取用户在不一定需要用户身份验证的页面上的声明,因为这些用户由于 Authorize 属性而不再可以访问它.

我可以做些什么来强制我的页面使用 cookie 授权而不破坏我的 API 的 JWT 授权?

后端应用的配置如下:

public void Configure(IApplicationBuilder app, IApiVersionDescriptionProvider descriptionProvider, IWebHostEnvironment env)
{
    ...
    app.UseAuthentication();
    app.UseIdentityServer();
    app.UseAuthorization();
}
public void ConfigureServices(IServiceCollection services)
{
    services
        .AddDefaultIdentity<ApplicationUser>()
        .AddRoles<ApplicationRole>()
        .AddEntityFrameworkStores<ApplicationDbContext>();
    
    JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
    
    services.AddIdentityServer()
        .AddApiAuthorization<ApplicationUser, ApplicationDbContext>()
        .AddProfileService<ProfileService>();

    services.AddTransient<IIdentityService, IdentityService>();

    services.AddAuthentication()
        .AddIdentityServerJwt();

    return services;
}

【问题讨论】:

    标签: asp.net-core identityserver4


    【解决方案1】:

    就个人而言,我认为您应该将 IdentityServer 放在它自己的服务实例上,并将 ASP.NET Identity 和您的客户端应用程序分开。因为否则理解和排除故障将非常复杂。当你把它们都放在同一个服务中时,这将是一团糟。 :-)

    例如,将涉及许多 cookie,IdentityServer 发出自己的 cookie,而您的客户端/ASP.NET Identity 发出自己的 cookie。

    【讨论】:

      猜你喜欢
      • 2020-11-23
      • 2019-03-23
      • 2018-02-20
      • 2016-07-02
      • 1970-01-01
      • 2018-06-13
      • 2018-01-26
      • 2022-01-23
      相关资源
      最近更新 更多