为另一个网站创建身份验证 cookie(通过 Windows 身份验证)

问题描述 投票:0回答:1

我使用的是 ASP.NET Core 8(发布后将升级到 9)。

我有 2 个网站,第一个是使用 Windows 身份验证在公司网络内部访问的。同一站点的另一个副本位于面向外部的 Web 服务器上并使用 cookie 身份验证。

其中一个关键问题是当网站发生变化时,我需要在两个位置发布代码(相同的代码,只是不同的

AppSettings.Production.json
文件)。

我想要实现的是,我不是拥有运行 2 个不同身份验证方案的同一网站的 2 个副本,而是只有 1 个使用 cookie 的副本,但我有另一个使用 Windows 身份验证的网站,它为以下内容创建 cookie根据当前用户自动主站点。

这允许用户通过标准登录页面(外部网络)或使用 Windows 身份验证(内部访问)通过其他网站使用 cookie 设置进行登录。

为了尝试并存档此内容,我创建了一个包含 2 个网站的测试解决方案

  1. 具有 Windows 身份验证的 ASP.NET Core MVC
  2. 使用个人帐户身份验证选项的 ASP.NET Core Razor 页面

在Windows auth站点上,我在

Program.cs

中添加了以下代码
builder.Services.AddAuthentication(NegotiateDefaults.AuthenticationScheme)
          
.AddCookie("CookieAuthenticationScheme") // New ************

   .AddNegotiate();

builder.Services.AddDataProtection() // New (Added before var app = builder.Build())
    .PersistKeysToFileSystem(new DirectoryInfo(@"c:\KeyLocation"))
    .SetApplicationName("SharedCookieApp");

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

然后在

Home/Index
中,我添加了

public class HomeController : Controller
{
    public async Task<IActionResult> Index()
    {
        var c = HttpContext;
        var userName = c.User.Identity?.Name;

        if (userName != null)
        {
            userName = "[email protected]"; // Name match's user created in asp.net identity on other site
            IEnumerable<Claim> claims = [new(ClaimTypes.Name, userName)];            
            await c.SignInAsync("CookieAuthenticationScheme", new ClaimsPrincipal(new ClaimsIdentity(claims, "CookieAuthenticationScheme")));
        }

        var Referer = Redirect("https://localhost:7207");  
        return Referer;
    }
}

然后在使用cookie的主网站中,我将以下内容添加到

Program.cs

builder.Services.AddDataProtection()
    .PersistKeysToFileSystem(new DirectoryInfo(@"c:\KeyLocation"))
    .SetApplicationName("SharedCookieApp");

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

但是,在 Windows 身份验证站点中创建的 cookie 无法登录到主网站。

如有任何帮助,我们将不胜感激

c# authentication windows-authentication asp.net-core-8 cookie-authentication
1个回答
0
投票

在我需要使用的 win auth 网站上

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

在使用Asp.net core身份的cookie站点上,我需要添加

builder.Services.ConfigureApplicationCookie(options => {
    options.Cookie.Name = ".CompanyName.SharedCookie";
});
© www.soinside.com 2019 - 2024. All rights reserved.