user3900456
user3900456

Reputation: 2003

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.

Upvotes: 15

Views: 5252

Answers (1)

Tarun Lalwani
Tarun Lalwani

Reputation: 146510

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

Upvotes: 8

Related Questions