前言、
已经好多天没写博客了,鉴于空闲无聊之时又兴起想写写博客,也当是给自己做个笔记。过了这么些天,我的文笔还是依然那么烂就请多多谅解了。今天主要是分享一下在使用.net core2.0下的实际遇到的情况。在使用webAPI时用了IDentity做用户验证。官方文档是的是用EF存储数据来使用dapper,因为个人偏好原因所以不想用EF。于是乎就去折腾。改成使用dapper做数据存储。于是就有了以下的经验。
一、使用IDentity服务
先找到Startup.cs 这个类文件 找到 ConfigureServices 方法
services.AddIDentity<ApplicationUser,ApplicationRole>().AddDefaultTokenProvIDers();//添加IDentityservices.AddTransIEnt<IUserStore<ApplicationUser>,CustomUserStore>();services.AddTransIEnt<IRoleStore<ApplicationRole>,CustomroleStore>();string connectionString = Configuration.GetConnectionString("sqlConnectionStr");services.AddTransIEnt<sqlConnection>(e => new sqlConnection(connectionString));services.AddTransIEnt<DapperUserstable>();
然后在 Configure 方法 的 app.UseMvc() 前加入下列代码,net core 1.0的时候是app.UseIDentity() 现在已经弃用改为以下方法。
//使用验证app.UseAuthentication();
这里的 ApplicationUser 是自定义的一个用户模型 具体是继承 IDentityUser 继承它的一些属性
public class ApplicationUser :IDentityUser { public string AuthenticationType { get; set; } public bool IsAuthenticated { get; set; } public string name { get; set; } }
这里的 CustomUserStore 是自定义提供用户的所有数据 *** 作的方法的类它需要继承三个接口:IUserStore,IUserPasswordStore,IUserEmailStore
IUserStore<TUser>接口是在用户存储中必须实现的唯一接口。 它定义了用于创建、 更新、 删除和检索用户的方法。
IUserPasswordStore<TUser>接口定义实现以保持经过哈希处理的密码的方法。 它包含用于获取和设置工作经过哈希处理的密码,以及用于指示用户是否已设置密码的方法的方法。
IUserEmailStore<TUser>接口定义实现以存储用户电子邮件地址的方法。 它包含用于获取和设置的电子邮件地址和是否确认电子邮件的方法。
这里跟.net core 1.0的实现接口方式有点不同。需要多实现 IUserEmailStore 才能不报错
具体代码如下。以供大家参考。
CustomUserStore
using Microsoft.AspNetCore.IDentity;using System;using System.Threading.Tasks;using System.Threading;namespace YepMarsCRM.Web.CustomProvIDer{ /// <summary> /// This store is only partially implemented. It supports user creation and find methods. /// </summary> public class CustomUserStore : IUserStore<ApplicationUser>,IUserPasswordStore<ApplicationUser>,IUserEmailStore<ApplicationUser> { private Readonly DapperUserstable _userstable; public CustomUserStore(DapperUserstable userstable) { _userstable = userstable; } #region createuser public async Task<IDentityResult> CreateAsync(ApplicationUser user,CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); if (user == null) throw new ArgumentNullException(nameof(user)); return await _userstable.CreateAsync(user); } #endregion public async Task<IDentityResult> DeleteAsync(ApplicationUser user,CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); if (user == null) throw new ArgumentNullException(nameof(user)); return await _userstable.DeleteAsync(user); } public voID dispose() { } public Task<ApplicationUser> FindByEmailAsync(string normalizedEmail,CancellationToken cancellationToken) { throw new NotImplementedException(); } public async Task<ApplicationUser> FindByIDAsync(string userID,CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); if (userID == null) throw new ArgumentNullException(nameof(userID)); GuID IDGuID; if (!GuID.TryParse(userID,out IDGuID)) { throw new ArgumentException("Not a valID GuID ID",nameof(userID)); } return await _userstable.FindByIDAsync(IDGuID); } public async Task<ApplicationUser> FindBynameAsync(string username,CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); if (username == null) throw new ArgumentNullException(nameof(username)); return await _userstable.FindBynameAsync(username); } public Task<string> GetEmailAsync(ApplicationUser user,CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (user == null) throw new ArgumentNullException(nameof(user)); return Task.Fromresult(user.Email); } public Task<bool> GetEmailConfirmedAsync(ApplicationUser user,CancellationToken cancellationToken) { throw new NotImplementedException(); } public Task<string> GetnormalizedEmailAsync(ApplicationUser user,CancellationToken cancellationToken) { throw new NotImplementedException(); } public Task<string> GetnormalizedUsernameAsync(ApplicationUser user,CancellationToken cancellationToken) { throw new NotImplementedException(); } public Task<string> getpasswordHashAsync(ApplicationUser user,CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (user == null) throw new ArgumentNullException(nameof(user)); return Task.Fromresult(user.PasswordHash); } public Task<string> GetUserIDAsync(ApplicationUser user,CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (user == null) throw new ArgumentNullException(nameof(user)); return Task.Fromresult(user.ID.ToString()); } public Task<string> GetUsernameAsync(ApplicationUser user,CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (user == null) throw new ArgumentNullException(nameof(user)); return Task.Fromresult(user.Username); } public Task<bool> HasPasswordAsync(ApplicationUser user,CancellationToken cancellationToken) { throw new NotImplementedException(); } public Task SetEmailAsync(ApplicationUser user,string email,CancellationToken cancellationToken) { throw new NotImplementedException(); } public Task SetEmailConfirmedAsync(ApplicationUser user,bool confirmed,CancellationToken cancellationToken) { throw new NotImplementedException(); } public Task SetnormalizedEmailAsync(ApplicationUser user,string normalizedEmail,CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (user == null) throw new ArgumentNullException(nameof(user)); if (normalizedEmail == null) throw new ArgumentNullException(nameof(normalizedEmail)); user.normalizedEmail = normalizedEmail; return Task.Fromresult<object>(null); } public Task SetnormalizedUsernameAsync(ApplicationUser user,string normalizedname,CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (user == null) throw new ArgumentNullException(nameof(user)); if (normalizedname == null) throw new ArgumentNullException(nameof(normalizedname)); user.normalizedUsername = normalizedname; return Task.Fromresult<object>(null); } public Task SetPasswordHashAsync(ApplicationUser user,string passwordHash,CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (user == null) throw new ArgumentNullException(nameof(user)); if (passwordHash == null) throw new ArgumentNullException(nameof(passwordHash)); user.PasswordHash = passwordHash; return Task.Fromresult<object>(null); } public Task SetUsernameAsync(ApplicationUser user,string username,CancellationToken cancellationToken) { throw new NotImplementedException(); } public Task<IDentityResult> UpdateAsync(ApplicationUser user,CancellationToken cancellationToken) { return _userstable.UpdateAsync(user); } }}
二、使用使用dapper做数据存储
接着就是使用dapper做数据存储。该类的方法都是通过 CustomUserStore 调用去 *** 作数据库的。具体代码如下。根据实际的用户表去 *** 作dapper即可。
DapperUserstable
using Microsoft.AspNetCore.IDentity;using System.Threading.Tasks;using System.Threading;using System.Data.sqlClIEnt;using System;using Dapper;using YepMarsCRM.Enterprise.DataBase.Model;using YepMarsCRM.Enterprise.DataBase.Data;namespace YepMarsCRM.Web.CustomProvIDer{ public class DapperUserstable { private Readonly sqlConnection _connection; private Readonly Sys_AccountData _sys_AccountData; public DapperUserstable(sqlConnection connection) { _connection = connection; _sys_AccountData = new Sys_AccountData(); } private Sys_Account ApplicationUserToAccount(ApplicationUser user) { return new Sys_Account { ID = user.ID,Username = user.Username,PasswordHash = user.PasswordHash,Email = user.Email,EmailConfirmed = user.EmailConfirmed,PhoneNumber = user.PhoneNumber,PhoneNumberConfirmed = user.PhoneNumberConfirmed,LockoutEnd = user.LockoutEnd?.DateTime,LockoutEnabled = user.LockoutEnabled,AccessFailedCount = user.AccessFailedCount,}; } #region createuser public async Task<IDentityResult> CreateAsync(ApplicationUser user) { int rows = await _sys_AccountData.InsertAsync(ApplicationUserToAccount(user)); if (rows > 0) { return IDentityResult.Success; } return IDentityResult.Failed(new IDentityError { Description = $"Could not insert user {user.Email}." }); } #endregion public async Task<IDentityResult> DeleteAsync(ApplicationUser user) { //string sql = "DELETE FROM Sys_Account WHERE ID = @ID"; //int rows = await _connection.ExecuteAsync(sql,new { user.ID }); int rows = await _sys_AccountData.DeleteForPKAsync(ApplicationUserToAccount(user)); if (rows > 0) { return IDentityResult.Success; } return IDentityResult.Failed(new IDentityError { Description = $"Could not delete user {user.Email}." }); } public async Task<ApplicationUser> FindByIDAsync(GuID userID) { string sql = "SELECT * FROM Sys_Account WHERE ID = @ID;"; return await _connection.querySingleOrDefaultAsync<ApplicationUser>(sql,new { ID = userID }); } public async Task<ApplicationUser> FindBynameAsync(string username) { string sql = "SELECT * FROM Sys_Account WHERE Username = @Username;"; return await _connection.querySingleOrDefaultAsync<ApplicationUser>(sql,new { Username = username }); //var user = new ApplicationUser() { Username = username,Email = username,EmailConfirmed = false }; //user.PasswordHash = new PasswordHasher<ApplicationUser>().HashPassword(user,"test"); //return await Task.Fromresult(user); } public async Task<IDentityResult> UpdateAsync(ApplicationUser applicationUser) { var user = ApplicationUserToAccount(applicationUser); var result = await _sys_AccountData.UpdateForPKAsync(user); if (result > 0) { return IDentityResult.Success; } return IDentityResult.Failed(new IDentityError { Description = $"Could not update user {user.Email}." }); } }}
三、使用UserManager、SignInManager验证 *** 作
新建一个 AccountController 控制器 并在构造函数中获取 依赖注入的对象 UserManager 与 SignInManager 如下:
[Authorize] public class AccountController : Controller { private Readonly UserManager<ApplicationUser> _userManager; private Readonly SignInManager<ApplicationUser> _signInManager; private Readonly ILogger _logger;public AccountController(UserManager<ApplicationUser> userManager,SignInManager<ApplicationUser> signInManager,ILoggerFactory loggerFactory) { _userManager = userManager; _signInManager = signInManager; _logger = loggerFactory.CreateLogger<AccountController>(); } }
SignInManager 是提供用户登录登出的API ,UserManager 是提供用户管理的API。
接着来实现一下简单的登录登出。
/// <summary> /// 登录 /// </summary> [httpPost] [AllowAnonymous] public async Task<IActionResult> Login(ReqLoginModel req) { var Json = new JsonResultModel<object>(); if (ModelState.IsValID) { var result = await _signInManager.PasswordSignInAsync(req.Username,req.Password,isPersistent: true,lockoutOnFailure: false); if (result.Succeeded) { Json.code = "200"; Json.message = "登录成功"; } else { Json.code = "400"; Json.message = "登录失败"; } if (result.IsLockedOut) { Json.code = "401"; Json.message = "账户密码已错误3次,账户被锁定,请30分钟后再尝试"; } } else { var errorMessges = ModelState.GetErrorMessage(); Json.code = "403"; Json.message = string.Join(",",errorMessges); } return Json.ToJsonResult(); }
/// <summary> /// 登出 /// </summary> /// <returns></returns> [httpPost] public async Task<IActionResult> logout() {await _signInManager.SignOutAsync(); var Json = new JsonResultModel<object>() { code = "200",data = null,message = "登出成功",remark = string.Empty }; return Json.ToJsonResult(); }
四、使用IDentity配置
在 ConfigureServices 方法中加入
services.Configure<IDentityOptions>(options => { // 密码配置 options.Password.requiredigit = false;//是否需要数字(0-9). options.Password.requiredLength = 6;//设置密码长度最小为6 options.Password.RequireNonAlphanumeric = false;//是否包含非字母或数字字符。 options.Password.RequireUppercase = false;//是否需要大写字母(A-Z). options.Password.RequireLowercase = false;//是否需要小写字母(a-z). //options.Password.requiredUniqueChars = 6; // 锁定设置 options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30);//账户锁定时长30分钟 options.Lockout.MaxFailedAccessAttempts = 3;//10次失败的尝试将账户锁定 //options.Lockout.AllowedForNewUsers = true; // 用户设置 options.User.RequireUniqueEmail = false; //是否Email地址必须唯一 }); services.ConfigureApplicationcookie(options => { // cookie settings options.cookie.httpOnly = true; //options.cookie.Expiration = TimeSpan.FromMinutes(30);//30分钟 options.cookie.Expiration = TimeSpan.FromHours(12);//12小时 options.LoginPath = "/API/Account/NotLogin"; // If the LoginPath is not set here,ASP.NET Core will default to /Account/Login //options.logoutPath = "/API/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; });
五、其他
在实现的过程中遇到一些小状况。例如IDentity不生效。是因为未在app.UseMvc() 之前使用造成的。 如果未登录会造成跳转。后来查看了.net core IDentity 的源码后 发现 如果是AJAX情况下 不会跳转而时 返回401的状态码页面。
然后就是IDenetity的密码加密 是用 PasswordHasher 这个类去加密的。如果想用自己的加密方式。只能通过继承接口去更改原本的方式。然后大致说到这么些。也当是给自己做做笔记。做得不好请大家多给点意见。多多谅解。谢谢。
以上这篇.net core2.0下使用IDentity改用dapper存储数据(实例讲解)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持编程小技巧。
总结以上是内存溢出为你收集整理的.net core2.0下使用Identity改用dapper存储数据(实例讲解)全部内容,希望文章能够帮你解决.net core2.0下使用Identity改用dapper存储数据(实例讲解)所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)