如何覆盖PasswordSignInAsync以在查找用户时添加TenantId

时间:2017-05-13 03:51:04

标签: asp.net-mvc asp.net-identity

我需要在PasswordSignInAsync中登录用户时添加TenantId过滤器,因为我们的UserName对每个租户只是唯一的。我怎样才能实现这个或任何其他选择?

2 个答案:

答案 0 :(得分:2)

在调用PasswordSignInAsync方法之前,您应该获取用户,然后检查tenantId。我想你有这样的方法:

public bool SingInUser(string userName, string password, int tenantId)
{
    var user = userManager.FindByNameAsync(userName);
    if(user == null)
        return false;

    if(user.TenantId != tenantId)
        return false;

    var signInResult = signInManager.PasswordSignInAsync(user, password, false);
    .
    .
    .
}

答案 1 :(得分:1)

因为每次您需要按名称查找用户时,您需要将其与tenantId相关联,最佳做法是创建自定义用户商店,并将其命名为CustomUserStore派生自UserStore<ApplicationUser>并覆盖FindByNameAsync方法。

所以新课程CustomUserStore将如下所示:

public class CustomUserStore : UserStore<ApplicationUser>
{
    public CustomUserStore()
    {
    }

    public CustomUserStore(DbContext context) : base(context)
    {
    }

    public override Task<ApplicationUser> FindByNameAsync(string userName)
    {
        // here you need to get the tenantId
        var tenantId = ...

        return GetUserAggregateAsync(u => u.TenantId == tenantId && u.UserName.ToUpper() == userName.ToUpper());
    }
}

在实例化ApplicationUserManager实例时,您需要使用CustomStore,如下所示:

var manager = new ApplicationUserManager(new CustomUserStore(context.Get<ApplicationDbContext>()));

由于ASP.Net Identiy中的许多方法需要在内部执行FindByUserNameAsync,因此使用 Mohsen Esmailpour 解决方案,您最终将为每个ASP.Net Identiy创建自定义方法涉及了解我们拥有哪个用户以及与之关联的tenantId的方法。创建一个自定义商店可以避免那种不可维护的代码。