【问题标题】:Identity user manager find by phonenumber身份用户管理器通过电话号码查找
【发布时间】:2017-11-24 08:38:29
【问题描述】:

在aspnet core identity2.0中,有没有办法通过电话号码找到用户? UserManager 可以通过用户名和电子邮件找到用户,但没有通过电话找到,甚至更好的是,提供了一个通用的find(Func<TUser, bool>) 函数。当用户注册电话时,需要检查给定的电话号码是否已经存在,因为一个电话不能被两个用户使用。

编辑

开始验证码:

services.AddIdentity<AccountUser, IdentityRole>()
            .AddEntityFrameworkStores<AccountDbContext>()
            .AddDefaultTokenProviders();
services.AddAuthentication().AddJwtBearer(...);

【问题讨论】:

  • 你的 startup.Auth 是什么样的?您是否覆盖了任何 OWIN 组件?如果没有,您将需要创建一个新的自定义 UserStore,如果您希望在 UserManager 中使用这个,也可能需要一个新的。
  • 我没有使用OWIN,只是身份,你能详细说明一下UserStore吗?
  • 现在我想起来了。为什么不直接查询表?您可以跳过一大堆障碍来覆盖所有身份验证组件,但如果您真的想知道该用户名是否唯一,只需检查数据库即可?
  • 是的,对,我在 api 控制器中得到了 DbContext,所以无论如何应该可以查询。不应该专注于 UserManager 方法,谢谢!

标签: c# asp.net-core asp.net-identity


【解决方案1】:

如果您想要求唯一的电话号码,您可以在 ApplicationDbContext(或您用作 IdentityDbContext 的任何上下文)中添加此方法:

protected override DbEntityValidationResult ValidateEntity(DbEntityEntry entityEntry, IDictionary<object, object> items)
{
    if (entityEntry != null && entityEntry.State == EntityState.Added)
    {
        var errors = new List<DbValidationError>();
        var user = entityEntry.Entity as ApplicationUser;
        //check for uniqueness of phone number
        if (user != null)
        {
            if (Users.Any(u => String.Equals(u.PhoneNumber, user.PhoneNumber)))
            {
                errors.Add(new DbValidationError("User",user.PhoneNumber+" is already registered."));
            }
        }
    }
    return base.ValidateEntity(entityEntry, items); //check for uniqueness of user name and email and return result
}

继承的base.ValidateEntity 方法用于检查以确保用户名和电子邮件是唯一的(如果您在配置中指定了这些选项)。

对于 using 语句,您似乎需要:

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Validation;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;

至于您提出的确切问题:要访问电话号码,您需要直接访问数据上下文。据我所知,UserManager 甚至 UserStore 都没有实现这样的方法,尽管您可以定义自己的用户存储类继承自 UserStore 来添加这样的方法。

【讨论】:

    【解决方案2】:

    使用此代码

    UserStoreCustom.cs

     public class UserStoreCustom : UserStore<User>
        {
            public UserStoreCustom(ApplicationDbContext context, IdentityErrorDescriber describer = null)
                : base(context, describer)
            {
    
            }
            public virtual Task<User> FindByPhoneNumberAsync(string PhoneNumber, CancellationToken cancellationToken = default(CancellationToken))
            {
                cancellationToken.ThrowIfCancellationRequested();
                ThrowIfDisposed();
                return Users.FirstOrDefaultAsync(u => u.PhoneNumber == PhoneNumber, cancellationToken);
            }
    

    Startup.cs

    services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(configuration.GetConnectionString("DataCenter")));
       
                services.AddIdentity<User, IdentityRole>(option =>
                {
                    // configure identity options
                    option.Password.RequireDigit = false;
                    option.Password.RequireLowercase = false;
                    option.Password.RequireUppercase = false;
                    option.Password.RequireNonAlphanumeric = false;
                    option.Password.RequiredLength = 4;
                    option.SignIn.RequireConfirmedPhoneNumber = true;
                })
    
                    .AddRoles<IdentityRole>()
                    .AddRoleManager<RoleManager<IdentityRole>>()
                     .AddEntityFrameworkStores<ApplicationDbContext>()
                    .AddUserStore<UserStoreCustom>()
                    .AddDefaultTokenProviders();
    
                services.AddSingleton<UserStoreCustom>();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-04-07
      • 2020-07-12
      • 1970-01-01
      • 1970-01-01
      • 2019-09-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多