如何在外部管理(添加)ASP.NET Core 3.1 应用程序的用户

How to manage (add) users for ASP.NET Core 3.1 application externally

很抱歉这里没有提供代码,因为我完全没有想到这个想法。

上下文:我开发了两个应用程序,都是 ASP.NET Core 3.1,我们称它们为 A 和 B。

A 是一个网站,暴露在互联网上。只有拥有有效用户帐户的用户才能访问。不可能在应用程序 A 中注册一个用户。

B 是一个内部(内联网)网站。 (使用 Active Directory 进行身份验证。)我希望能够从应用程序 B 为应用程序 A 创建用户。

应用程序 A 与 Active Directory 无关,我使用 ASP.NET 核心的正常内置用户管理。

是否可以通过Entity Framework将用户从应用程序B输入到应用程序A?还是有更好的方法?如果它与 Entity Framework 一起使用,我将如何获得应用程序 A 用于加盐密码的加盐值?

澄清一下:我对应用程序 B 的用户身份验证或注册没有任何疑问,一切正常。

由于在您提到的评论中您更关心盐的存储方式,我假设您已将 EF 指向 Application A 成员数据库设置并专注于此哈希位。我假设您使用 UserManager 来管理您的密码。

如果您了解一下密码是如何 stored and verified, you will notice both operations end up relying on PasswordHasher 来完成这项工作的。它被框架依赖注入到您的 UserManager 中并查看实现:

private static byte[] HashPasswordV3(
      string password,
      RandomNumberGenerator rng,
      KeyDerivationPrf prf,
      int iterCount,
      int saltSize,
      int numBytesRequested)
    {
      byte[] numArray1 = new byte[saltSize];
      rng.GetBytes(numArray1);
      byte[] numArray2 = Microsoft.AspNetCore.Cryptography.KeyDerivation.KeyDerivation.Pbkdf2(password, numArray1, prf, iterCount, numBytesRequested);
      byte[] buffer = new byte[13 + numArray1.Length + numArray2.Length];
      buffer[0] = (byte) 1;

      PasswordHasher<TUser>.WriteNetworkByteOrder(buffer, 1, (uint) prf); // hash type
      PasswordHasher<TUser>.WriteNetworkByteOrder(buffer, 5, (uint) iterCount); // number of iterations
      PasswordHasher<TUser>.WriteNetworkByteOrder(buffer, 9, (uint) saltSize); // salt size (although not configurable in this implementation)
      Buffer.BlockCopy((Array) numArray1, 0, (Array) buffer, 13, numArray1.Length); // salt goes here
      Buffer.BlockCopy((Array) numArray2, 0, (Array) buffer, 13 + saltSize, numArray2.Length); // password hash goes here
      return buffer; // this gets Base64-encoded upstream
    }

似乎盐只是一个随机的 16 字节数组,与 hashhashing functionnumber of iterations used 一起存储,因此一个应用程序创建的哈希应该是可读的只要 PasswordHasherCompatibilityMode and generating OS 相同,就可以由另一个人代为完成,无需任何额外工作。

这里还有一点要注意,因为 PasswordHasherdependency-injected, you actually can replace it with your own implementation if need be. Hopefully poking around PasswordHasher 为您提供了足够的上下文。

您可以使用以下方法轻松创建密码哈希

public string CreateHash(TUser user, string password)
{
    var hasher = new PasswordHasher<TUser>();

    return (hasher.HashPassword(user, password));
}

用户对象甚至不能是您要更改密码的对象。