Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Machine key in asp.net core 2.0?

I have the same asp.net core 2 app running on 2 different servers but using the same database to store users and etc.

The problem is that if I create and set a user password in one server, the other server running the same app returns invalid password and vice-versa.

I had this problem a few years ago with an asp.net 4 app and I fixed it by setting the same machine key for both apps.

I heard about data protection api, but I can't find where to just tell it to use the same encryption key, instead I find complex examples that confuses me and all I need is to make both servers understand each other's encryption.

like image 768
user3900456 Avatar asked Oct 21 '17 06:10

user3900456


People also ask

What is ASP NET MachineKey?

The MachineKey class provides methods that expose the hashing and encryption logic that ASP.NET provides. For information about which encryption and hashing algorithms ASP.NET uses, and the key values that it uses with them, see machineKey Element (ASP.NET Settings Schema).

What is the use of MachineKey?

Use the Machine Key feature page to configure hashing and encryption settings used for application services, such as view state, Forms authentication, membership and roles, and anonymous identification. Machine keys are also used to verify out-of-process session state identification.

Is MachineKey protect secure?

The Protect method performs the appropriate operation and securely protects the data. Ciphertext data produced by this method can only be deciphered by the Unprotect method.


1 Answers

You can keep one server as primary and one as secondary. In the secondary server disable auto key generation

using Microsoft.AspNetCore.DataProtection;

public void ConfigureServices(IServiceCollection services)
{
     services.AddDataProtection().DisableAutomaticKeyGeneration();
}

Or you can persist them to Redis

public void ConfigureServices(IServiceCollection services)
{
    // sad but a giant hack :(
    // https://github.com/StackExchange/StackExchange.Redis/issues/410#issuecomment-220829614
    var redisHost = Configuration.GetValue<string>("Redis:Host");
    var redisPort = Configuration.GetValue<int>("Redis:Port");
    var redisIpAddress = Dns.GetHostEntryAsync(redisHost).Result.AddressList.Last();
    var redis = ConnectionMultiplexer.Connect($"{redisIpAddress}:{redisPort}");

    services.AddDataProtection().PersistKeysToRedis(redis, "DataProtection-Keys");
    services.AddOptions();

    // ...
}

A detailed article is available on the same

http://www.tugberkugurlu.com/archive/asp-net-core-authentication-in-a-load-balanced-environment-with-haproxy-and-redis

PS: The code posted above is from the same articles, so that if link goes the down, the answer is still complete

like image 112
Tarun Lalwani Avatar answered Oct 13 '22 01:10

Tarun Lalwani