最新文章專題視頻專題問(wèn)答1問(wèn)答10問(wèn)答100問(wèn)答1000問(wèn)答2000關(guān)鍵字專題1關(guān)鍵字專題50關(guān)鍵字專題500關(guān)鍵字專題1500TAG最新視頻文章推薦1 推薦3 推薦5 推薦7 推薦9 推薦11 推薦13 推薦15 推薦17 推薦19 推薦21 推薦23 推薦25 推薦27 推薦29 推薦31 推薦33 推薦35 推薦37視頻文章20視頻文章30視頻文章40視頻文章50視頻文章60 視頻文章70視頻文章80視頻文章90視頻文章100視頻文章120視頻文章140 視頻2關(guān)鍵字專題關(guān)鍵字專題tag2tag3文章專題文章專題2文章索引1文章索引2文章索引3文章索引4文章索引5123456789101112131415文章專題3
問(wèn)答文章1 問(wèn)答文章501 問(wèn)答文章1001 問(wèn)答文章1501 問(wèn)答文章2001 問(wèn)答文章2501 問(wèn)答文章3001 問(wèn)答文章3501 問(wèn)答文章4001 問(wèn)答文章4501 問(wèn)答文章5001 問(wèn)答文章5501 問(wèn)答文章6001 問(wèn)答文章6501 問(wèn)答文章7001 問(wèn)答文章7501 問(wèn)答文章8001 問(wèn)答文章8501 問(wèn)答文章9001 問(wèn)答文章9501
當(dāng)前位置: 首頁(yè) - 科技 - 知識(shí)百科 - 正文

.net core2.0下使用Identity改用dapper存儲(chǔ)數(shù)據(jù)(實(shí)例講解)

來(lái)源:懂視網(wǎng) 責(zé)編:小采 時(shí)間:2020-11-27 22:35:12
文檔

.net core2.0下使用Identity改用dapper存儲(chǔ)數(shù)據(jù)(實(shí)例講解)

.net core2.0下使用Identity改用dapper存儲(chǔ)數(shù)據(jù)(實(shí)例講解):前言、 已經(jīng)好多天沒(méi)寫(xiě)博客了,鑒于空閑無(wú)聊之時(shí)又興起想寫(xiě)寫(xiě)博客,也當(dāng)是給自己做個(gè)筆記。過(guò)了這么些天,我的文筆還是依然那么爛就請(qǐng)多多諒解了。今天主要是分享一下在使用.net core2.0下的實(shí)際遇到的情況。在使用webapi時(shí)用了identity做用戶驗(yàn)證。官方文
推薦度:
導(dǎo)讀.net core2.0下使用Identity改用dapper存儲(chǔ)數(shù)據(jù)(實(shí)例講解):前言、 已經(jīng)好多天沒(méi)寫(xiě)博客了,鑒于空閑無(wú)聊之時(shí)又興起想寫(xiě)寫(xiě)博客,也當(dāng)是給自己做個(gè)筆記。過(guò)了這么些天,我的文筆還是依然那么爛就請(qǐng)多多諒解了。今天主要是分享一下在使用.net core2.0下的實(shí)際遇到的情況。在使用webapi時(shí)用了identity做用戶驗(yàn)證。官方文

前言、

已經(jīng)好多天沒(méi)寫(xiě)博客了,鑒于空閑無(wú)聊之時(shí)又興起想寫(xiě)寫(xiě)博客,也當(dāng)是給自己做個(gè)筆記。過(guò)了這么些天,我的文筆還是依然那么爛就請(qǐng)多多諒解了。今天主要是分享一下在使用.net core2.0下的實(shí)際遇到的情況。在使用webapi時(shí)用了identity做用戶驗(yàn)證。官方文檔是的是用EF存儲(chǔ)數(shù)據(jù)來(lái)使用dapper,因?yàn)閭€(gè)人偏好原因所以不想用EF。于是乎就去折騰。改成使用dapper做數(shù)據(jù)存儲(chǔ)。于是就有了以下的經(jīng)驗(yàn)。

一、使用Identity服務(wù)

先找到Startup.cs 這個(gè)類文件 找到 ConfigureServices 方法

services.AddIdentity<ApplicationUser, ApplicationRole>().AddDefaultTokenProviders();//添加Identity
services.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的時(shí)候是app.UseIdentity() 現(xiàn)在已經(jīng)棄用改為以下方法。

//使用驗(yàn)證
app.UseAuthentication();

這里的 ApplicationUser 是自定義的一個(gè)用戶模型 具體是繼承 IdentityUser 繼承它的一些屬性

public class ApplicationUser :IdentityUser
 {
 public string AuthenticationType { get; set; }
 public bool IsAuthenticated { get; set; }
 public string Name { get; set; }
 }

這里的 CustomUserStore 是自定義提供用戶的所有數(shù)據(jù)操作的方法的類它需要繼承三個(gè)接口:IUserStore,IUserPasswordStore,IUserEmailStore

IUserStore<TUser>接口是在用戶存儲(chǔ)中必須實(shí)現(xiàn)的唯一接口。 它定義了用于創(chuàng)建、 更新、 刪除和檢索用戶的方法。

IUserPasswordStore<TUser>接口定義實(shí)現(xiàn)以保持經(jīng)過(guò)哈希處理的密碼的方法。 它包含用于獲取和設(shè)置工作經(jīng)過(guò)哈希處理的密碼,以及用于指示用戶是否已設(shè)置密碼的方法的方法。

IUserEmailStore<TUser>接口定義實(shí)現(xiàn)以存儲(chǔ)用戶電子郵件地址的方法。 它包含用于獲取和設(shè)置的電子郵件地址和是否確認(rèn)電子郵件的方法。

這里跟.net core 1.0的實(shí)現(xiàn)接口方式有點(diǎn)不同。需要多實(shí)現(xiàn) IUserEmailStore 才能不報(bào)錯(cuò)

具體代碼如下。以供大家參考。

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做數(shù)據(jù)存儲(chǔ)

接著就是使用dapper做數(shù)據(jù)存儲(chǔ)。該類的方法都是通過(guò) CustomUserStore 調(diào)用去操作數(shù)據(jù)庫(kù)的。具體代碼如下。根據(jù)實(shí)際的用戶表去操作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驗(yàn)證操作

新建一個(gè) AccountController 控制器 并在構(gòu)造函數(shù)中獲取 依賴注入的對(duì)象 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。

接著來(lái)實(shí)現(xiàn)一下簡(jiǎn)單的登錄登出。

/// <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 = "賬戶密碼已錯(cuò)誤3次,賬戶被鎖定,請(qǐng)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;//是否需要數(shù)字(0-9).
 options.Password.RequiredLength = 6;//設(shè)置密碼長(zhǎng)度最小為6
 options.Password.RequireNonAlphanumeric = false;//是否包含非字母或數(shù)字字符。
 options.Password.RequireUppercase = false;//是否需要大寫(xiě)字母(A-Z).
 options.Password.RequireLowercase = false;//是否需要小寫(xiě)字母(a-z).
 //options.Password.RequiredUniqueChars = 6;

 // 鎖定設(shè)置
 options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30);//賬戶鎖定時(shí)長(zhǎng)30分鐘
 options.Lockout.MaxFailedAccessAttempts = 3;//10次失敗的嘗試將賬戶鎖定
 //options.Lockout.AllowedForNewUsers = true;

 // 用戶設(shè)置
 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小時(shí)
 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;
 });

五、其他

在實(shí)現(xiàn)的過(guò)程中遇到一些小狀況。例如Identity不生效。是因?yàn)槲丛赼pp.UseMvc() 之前使用造成的。 如果未登錄會(huì)造成跳轉(zhuǎn)。后來(lái)查看了.net core Identity 的源碼后 發(fā)現(xiàn) 如果是ajax情況下 不會(huì)跳轉(zhuǎn)而時(shí) 返回401的狀態(tài)碼頁(yè)面。

然后就是Idenetity的密碼加密 是用 PasswordHasher 這個(gè)類去加密的。如果想用自己的加密方式。只能通過(guò)繼承接口去更改原本的方式。然后大致說(shuō)到這么些。也當(dāng)是給自己做做筆記。做得不好請(qǐng)大家多給點(diǎn)意見(jiàn)。多多諒解。謝謝。

以上這篇.net core2.0下使用Identity改用dapper存儲(chǔ)數(shù)據(jù)(實(shí)例講解)就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

聲明:本網(wǎng)頁(yè)內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問(wèn)題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com

文檔

.net core2.0下使用Identity改用dapper存儲(chǔ)數(shù)據(jù)(實(shí)例講解)

.net core2.0下使用Identity改用dapper存儲(chǔ)數(shù)據(jù)(實(shí)例講解):前言、 已經(jīng)好多天沒(méi)寫(xiě)博客了,鑒于空閑無(wú)聊之時(shí)又興起想寫(xiě)寫(xiě)博客,也當(dāng)是給自己做個(gè)筆記。過(guò)了這么些天,我的文筆還是依然那么爛就請(qǐng)多多諒解了。今天主要是分享一下在使用.net core2.0下的實(shí)際遇到的情況。在使用webapi時(shí)用了identity做用戶驗(yàn)證。官方文
推薦度:
  • 熱門(mén)焦點(diǎn)

最新推薦

猜你喜歡

熱門(mén)推薦

專題
Top