首页 > 解决方案 > .NET Core 3.1 中的机器密钥实现

问题描述

在 ASP.NET 中,我们通常会像这样将机器密钥添加到 web.config -

<machineKey validation="HMACSHA512" decryption="AES" validationKey="********" decryptionKey="******" />

有人可以告诉我如何在 ASP.NET Core 3.1 中做同样的事情吗?

标签: asp.net-coreasp.net-core-3.1.net-core-3.1

解决方案


要为站点上的多个 Web 应用程序启用 SSO(单点登录),请确保在所有 Web 应用程序的 Startup.cs 中添加 DataProtection 并设置相同的 ApplicationName,将密钥保存到相同的目录并使用相同的 cookie 名称像这样:

services
    .AddDataProtection()
    .SetApplicationName("MyWebSite") 
    .PersistKeysToFileSystem(new DirectoryInfo(@"C:\MyWebSite-keys"));

services
    .AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme,
        options =>
        {
                options.LoginPath = "/login/login";
                options.Cookie.Path = "/";
                options.Cookie.Name = "MyWebSite-Login";
            });

在 Core 中不再使用 machineKey,而不是 validationKey 和 decryptionKey,只会使用 masterkey,并且会在您指定的目录中自动创建。

在此之后,在登录应用程序 A 并请求应用程序 B 后,用户将保持登录状态。


推荐阅读