1
votes

In ASP.NET we would normally add a machine key to the web.config like this -

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

Can someone please advises me how can we do the same in ASP.NET Core 3.1?

3
Why do you need it in asp.net core?Julian
I am working on upgrading the ASP.NET application into Core 3.1. So need to configure the same machine key or any other approach for Core 3.1.Akhilesh Maithani

3 Answers

1
votes

To enable SSO (Single Sign On) for multiple web applications on your site make sure that in the Startup.cs of all your web applications you add DataProtection and set the same ApplicationName, save the keys to the same directory and use the same cookie name like this:

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";
            });

machineKey is no longer used in Core, instead of validationKey and decryptionKey only the masterkey will be used and will be created automatically in the directory you specify.

After this, after logging in application A and requesting application B the user will remain logged in.

0
votes

You will need the install this package: Microsoft.AspNetCore.DataProtection.SystemWeb It neeeds to be ASP.NET 4.5.1+.

Read more here: Replace the ASP.NET machineKey in ASP.NET Core

0
votes

In Asp.net Core Application, you can implementation the <machineKey> element using the Data Protection API.

To use the Data Protection API in asp.net core application, first, install the package Microsoft.AspNetCore.DataProtection.SystemWeb. You might meet a warning "Warning NU1701...This package may not be fully compatible with your project.", on my side, this warning will not influence us to use this package.

[Note] The new data protection system can only be installed into an existing ASP.NET application targeting .NET 4.5.1 or later. Installation will fail if the application targets .NET 4.5 or lower.

Then, register the Data Protection service in the Startup.cs file, like this:

        services.AddDataProtection().PersistKeysToFileSystem(new DirectoryInfo(@"D:\temp\temp-keys\"));

After running the application, the generate file content as below:

enter image description here

The above code was configured a file system-based key repository to store the machine key, you can also use Azure Storage, Redis, Registry or Entity Framework Core. More detail information, check the Key storage providers in ASP.NET Core