.Net Core Mvc中使用Identity

发布于 2018-02-05  254 次阅读


附下微软官方文档地址:点此查看

项目中要添加

Microsoft.AspNetCore.Identity.EntityFrameworkCore

Microsoft.AspNetCore.Identity

1.比如要扩展IdentityUser的字段

public class AppUser : IdentityUser
{
/// <summary>
/// 登录账号
/// </summary>
public string LoginName { get; set; }

/// <summary>
/// 真实姓名
/// </summary>
public string RealName { get; set; }
}

2.正常使用是继承自DBCONTEXT 使用identity的话就必须继承自IdentityDbContext,这样那个实体类什么的就都继承过来了,<>里填你定义的用户实体类,如果自己没扩展,就填默认的IdentityUser

public class lkWebContext : IdentityDbContext<AppUser> //注意AppUser

{

}

3.startup.cs中

ConfigureServices方法增加下列代码初始化配置

services.AddIdentity<AppUser, IdentityRole>() // AppUser就是你那个实体类 IdentityRole是Identity默认的
.AddEntityFrameworkStores<lkWebContext>()
.AddDefaultTokenProviders();

services.Configure<IdentityOptions>(options =>
{
// Password settings
options.Password.RequireDigit = true;
options.Password.RequiredLength = 8;
options.Password.RequireNonAlphanumeric = false;
options.Password.RequireUppercase = true;
options.Password.RequireLowercase = false;
options.Password.RequiredUniqueChars = 6;

// Lockout settings
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30);
options.Lockout.MaxFailedAccessAttempts = 10;
options.Lockout.AllowedForNewUsers = true;

// User settings
options.User.RequireUniqueEmail = true;
});

services.ConfigureApplicationCookie(options =>
{
// Cookie settings
options.Cookie.HttpOnly = true;
options.Cookie.Expiration = TimeSpan.FromDays(150);
options.LoginPath = "/Account/Login"; // If the LoginPath is not set here, ASP.NET Core will default to /Account/Login
options.LogoutPath = "/Account/Logout"; // If the LogoutPath is not set here, ASP.NET Core will default to /Account/Logout
options.AccessDeniedPath = "/Account/AccessDenied"; // If the AccessDeniedPath is not set here, ASP.NET Core will default to /Account/AccessDenied
options.SlidingExpiration = true;
});

Configure方法增加下列代码

app.UseAuthentication(); //使用Identity

4.然后就

Add-Migration initIdentity

Update-Database 执行完成后打开数据库就发现多出几张表 当然前提是你EF已经没问题的,这里不多说。

 

5.在用identity的时候发现他IdentityUser表的主键是Guid类型,让我用好不方便,我这里并不需要他,Guid和int各有优劣

然后说下怎么修改为都使用Int当主键类型

都类似这样就可以了

public class UserEntity : IdentityUser<int> {}

public class RoleEntity : IdentityRole<int>{}

注意 在DbContext也得修改

public class lkWebContext : IdentityDbContext<UserEntity, RoleEntity, int> { }

 

6.关于Identity中UserManage,SignManage等等的用法,我这里说一下我的使用方式

依赖注入,在构造函数里接收

还有一种方式是直接继承自UserManage

在Identity中全部都是异步

public partial class UserService : ServiceBase<UserEntity>, IUserService
{
public readonly ILoginLogService _loginLogService;
public readonly UserManager<UserEntity> _userManager;
public readonly SignInManager<UserEntity> _signInManager;
public readonly RoleManager<RoleEntity> _roleManage;

public UserService(ILoginLogService loginLogService,
UserManager<UserEntity> userManager,
SignInManager<UserEntity> signInManager,
RoleManager<RoleEntity> roleManage)
{
_loginLogService = loginLogService;
_userManager = userManager;
_signInManager = signInManager;
_roleManage = roleManage;
}

/// <summary>
/// 登陆
/// </summary>
/// <param name="dto">user实体</param>
/// <returns></returns>
public async Task<Result<UserDto>> Login(UserDto dto)
{
var result = new Result<UserDto>();
var signedUser = await _userManager.FindByNameAsync(dto.UserName);
var signInResult = await _signInManager.PasswordSignInAsync(signedUser, dto.Password, false, false);
if (signInResult.Succeeded)
{
var signedUserDto = MapTo<UserEntity, UserDto>(signedUser);
if (signedUserDto.Status == UserStatus.未激活)
result.msg = "登陆失败,账户未激活";
else if (signedUserDto.Status == UserStatus.禁用)
result.msg = "登陆失败,账户已禁用";
else if (signedUserDto.Status == UserStatus.已激活)
result.flag = true;
WebHelper.SetSession("CurrentUser", signedUserDto);
}
else
{
if (signInResult.IsNotAllowed)
result.msg = "登陆失败,不被允许";
else if (signInResult.IsLockedOut)
result.msg = "登陆失败,账户被锁";
else
result.msg = "登陆失败,请检查输入的信息";
}
//记录登录日志
await _loginLogService.Add(new LoginLogDto
{
UserId = dto.Id,
UserName = dto.UserName,
ClientIP = WebHelper.GetClientIP(),
ClientMac = WebHelper.GetClientMac(),
Description = result.msg
});
return result;

}

public async Task<Result<UserDto>> Register(UserDto dto)
{
var result = new Result<UserDto>();
var user = MapTo<UserDto, UserEntity>(dto);
var regResult = await _userManager.CreateAsync(user, dto.Password);
if (regResult.Succeeded)
result.flag = true;
else
{
foreach (var err in regResult.Errors)
{
result.msg += err.Description + "\n";
}
}
return result;
}
}

LoneKing