【问题标题】:.NET Core Shared Cookies.NET Core 共享 Cookie
【发布时间】:2021-11-25 12:25:30
【问题描述】:

我有带有 .NET Core Identity 的 .NET Core 应用程序。 我已将共享 cookie 设置为 Startup.cs:

services.AddIdentity<User, Role>()
    .AddEntityFrameworkStores<DataContext>()
    .AddDefaultTokenProviders();

services.ConfigureApplicationCookie(options =>
{
    options.Cookie.Name = ".AspNet.SharedCookie";
});

services.AddAuthentication()

...

app.UseAuthentication();
app.UseAuthorization();

我还有第二个 .NET Core 应用程序,我根本没有身份验证,但只想使用 SharedCookie,我在 Startup.cs 中做了以下操作:

services.AddAuthentication("Identity.Application")
    .AddCookie("Identity.Application", options =>
    {
        options.Cookie.Name = ".AspNet.SharedCookie";
    });

...

app.UseAuthentication();
app.UseAuthorization();

在控制器操作上我设置属性[Authorize]

我登录到第一个应用程序并转到第二个应用程序并看到错误 /Account/Login... 页面不存在。

是的,我没有那个页面,但为什么我会看到这个问题?我是否忘记在代码中添加任何内容? 还有一个问题:什么是 SharedCookie 字符串?它是随机字符串还是编码了一些用户数据?我可以从 SharedCookie 中提取任何信息,例如用户 ID 吗?

【问题讨论】:

    标签: .net-core cookies authorization cookie-authentication


    【解决方案1】:

    所以我的解决方案是向两个应用程序添加 DataProtection 步骤:

    if (!Env.IsDevelopment())
    {
        services.AddDataProtection()
            .PersistKeysToFileSystem("{PATH TO COMMON KEY RING FOLDER}")
            .SetApplicationName("SharedCookieApp");
    }
    

    还有一个问题:什么是 SharedCookie 字符串?它是随机字符串还是编码了一些用户数据?我可以从 SharedCookie 中提取任何信息,例如用户 ID 吗?

    是的,我可以通过以下方式提取用户的Id,Email:

    var id = HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier);
    var email = HttpContext.User.FindFirstValue(ClaimTypes.Email);
    

    【讨论】:

      猜你喜欢
      • 2020-08-28
      • 2020-05-18
      • 2020-06-02
      • 1970-01-01
      • 2019-01-22
      • 2019-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多