重慶分公司,新征程啟航
為企業提供網站建設、域名注冊、服務器等服務
為企業提供網站建設、域名注冊、服務器等服務
本例是用簡單角色驗證方式來通過用戶登錄后,獲取用戶角色,每種角色可以通過[Authorize(Roles = "admin,user")]在Action上來控制訪問的權限,也就是說,只有屬性這個角色才能訪問這個Action。
道先添加Microsoft.AspNetCore.Authentication.Cookies引用
創新互聯建站自成立以來,一直致力于為企業提供從網站策劃、網站設計、網站制作、做網站、電子商務、網站推廣、網站優化到為企業提供個性化軟件開發等基于互聯網的全面整合營銷服務。公司擁有豐富的網站建設和互聯網應用系統開發管理經驗、成熟的應用系統解決方案、優秀的網站開發工程師團隊及專業的網站設計師團隊。
在StartUp.cs的Configure方法中添加
//為驗證添加中間件 app.UseCookieAuthentication(new CookieAuthenticationOptions { //驗證方案名稱 AuthenticationScheme = "loginvalidate", //沒有權限時導航的登錄action LoginPath = new Microsoft.AspNetCore.Http.PathString("/login"), //訪問被拒絕后的acion AccessDeniedPath = new Microsoft.AspNetCore.Http.PathString("/Home/NoPermission"), AutomaticAuthenticate = true, AutomaticChallenge = true, SlidingExpiration = true });
HomeController中的登錄的action實現
using System.Collections.Generic; using System.Linq; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Authorization; using System.Security.Claims; namespace webAuth.Controllers { ////// 本Controller允許admin和user兩種角色可以訪問 /// [Authorize(Roles = "admin,user")] public class HomeController : Controller { public IActionResult Index() { return View(); } ////// aobout只允許user角色訪問 /// ///[Authorize(Roles = "user")] public IActionResult About() { var id = User.Claims.SingleOrDefault(c => c.Type == ClaimTypes.Sid).Value; ViewData["Message"] = "UserID:"+ id; return View(); } /// /// contact只允許admin角色訪問 /// ///[Authorize(Roles = "admin")] public IActionResult Contact() { var id=User.Claims.SingleOrDefault(c => c.Type == ClaimTypes.Sid).Value; ViewData["Message"] = "UserID:"+ id; return View(); } public IActionResult NoPermission() { return View(); } /// /// 允許所有登錄者 /// /// 如果用戶訪問的不是登錄頁,returnUrl將把這個url傳進來,待登錄成功后返回這個地址 ///[AllowAnonymous] [HttpGet("login")] public IActionResult Login(string returnUrl) { //判斷是否驗證 if (!HttpContext.User.Identity.IsAuthenticated) { //把返回地址保存在前臺的hide表單中 ViewBag.returnUrl = returnUrl; } ViewBag.error = null; return View(); } /// /// 允許所有登錄者 /// /// 用戶名 /// 密碼 /// 返回u ///[AllowAnonymous] [HttpPost("login")] public IActionResult Login(string username, string password, string returnUrl) { //從數據庫驗證用戶,關取出用戶所需要信息 var users = new List () { new { ID = 1, UserName = "zsf",Password="111", Name = "張三豐", RoleTypeID = 1, RoleType = "admin", RoleTypeName = "管理員" }, new { ID = 2, UserName = "zwj",Password="222", Name = "張無忌", RoleTypeID = 2, RoleType = "user", RoleTypeName = "普通用戶" } }; var user = users.SingleOrDefault(u => u.UserName == username && u.Password == password); if (user!=null) { //登錄成功后,設置聲明 var claims = new Claim[] { new Claim(ClaimTypes.UserData,username), new Claim(ClaimTypes.Role,user.RoleType), new Claim(ClaimTypes.Name,user.Name), new Claim(ClaimTypes.Sid,user.ID.ToString()) }; HttpContext.Authentication.SignInAsync("loginvalidate", new ClaimsPrincipal(new ClaimsIdentity(claims, "Cookie"))); HttpContext.User = new ClaimsPrincipal(new ClaimsIdentity(claims)); return new RedirectResult(returnUrl == null ? "/" : returnUrl); } else { ViewBag.error = "用戶名或密碼錯誤!"; return View(); } } } }
Login.cshtml頁面如下:
@{ Layout = null; }登錄
如果在其他頁面使用User,可以像下面這樣使用
當前用戶:@User.Identity.Name
當然也可以從User中查到其他登錄時存儲的Claim的值
登錄成功后
登錄成功后訪問沒有權限頁面(當然可以不讓這種角色看到不能訪問的鏈接)