.net core中登錄認證---中間件認證


.net core中登錄認證---中間件認證  

介紹:這是基於授權認證中間件認證的示例

第一步:

在 app.UseRouting();之后,在app.UseEndpoints()之前,增加鑒權授權;
鑒權: app.UseAuthentication();---檢測用戶是否登錄
授權:app.UseAuthorization();//授權 檢測有沒有權限,是否能夠訪問后續的頁面功能

第二步:在ConfigureServices中中增加如下

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
    options.LoginPath = new PathString("/Login/Login"); //如果授權失敗,就跳轉到這個路徑去中

//options.AccessDeniedPath = new PathString("/Home/Privacy");
});//用cookie

第三步:第三步:指定哪些Action需要做鑒權授權,標記特性:標記在哪個Action上,哪個Action就能夠支持鑒權授權,也可以標記在控制器,全局;

[Microsoft.AspNetCore.Authorization.Authorize]

第四步: 登錄時使用鑒權

         [HttpPost]
     [AllowAnonymousAttribute] //這是匿名,加上他會避開權限檢查
public IActionResult Login(string name,string password) { string verifyCode = base.HttpContext.Session.GetString("CheckCode"); if (!string.IsNullOrEmpty(verifyCode)) { } #region 鑒權:鑒權,檢測有沒有登錄,登錄的是誰,賦值給User //rolelist 是登錄成功后用戶的角色---是來自於數據庫的查詢;不同的用戶會查詢出不同的角色; var rolelist = new List<string>() { "Admin", "Teacher", "Student" }; //ClaimTypes.Role就是做權限認證的標識; var claims = new List<Claim>()//鑒別你是誰,相關信息 { new Claim(ClaimTypes.Role,"Admin"), new Claim(ClaimTypes.Name,name), new Claim("password",password),//可以寫入任意數據 new Claim("Account","Administrator"), new Claim("role","admin"), new Claim("zhaoxi","zhaoxi"), new Claim("User","zhaoxi") }; foreach (var role in rolelist) { claims.Add(new Claim(ClaimTypes.Role, role)); } ClaimsPrincipal userPrincipal = new ClaimsPrincipal(new ClaimsIdentity(claims, "Customer")); HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, userPrincipal, new AuthenticationProperties { ExpiresUtc = DateTime.UtcNow.AddMinutes(30),//過期時間:30分鍾 }).Wait(); #endregion var user = HttpContext.User; return base.Redirect("/Home/Index"); }

第五步:鑒權授權角色授權,不同的用戶,可能會存在不同的角色,不同的角色,可能在訪問不同的頁面的時候,需要做不同攔截;----角色授權其實就是通過角色不同,做不同的權限攔截;

[Authorize(Roles = "Admin,Teacher,Student")]

六、用戶退出登錄

await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);

謝謝學習!!!關注我,每天進步一點點

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM