本例是用簡(jiǎn)單角色驗(yàn)證方式來(lái)通過(guò)用戶(hù)登錄后,獲取用戶(hù)角色,每種角色可以通過(guò)[Authorize(Roles = "admin,user")]在Action上來(lái)控制訪(fǎng)問(wèn)的權(quán)限,也就是說(shuō),只有屬性這個(gè)角色才能訪(fǎng)問(wèn)這個(gè)Action。
道先添加Microsoft.AspNetCore.Authentication.Cookies引用
創(chuàng)新互聯(lián)建站自成立以來(lái),一直致力于為企業(yè)提供從網(wǎng)站策劃、網(wǎng)站設(shè)計(jì)、網(wǎng)站制作、做網(wǎng)站、電子商務(wù)、網(wǎng)站推廣、網(wǎng)站優(yōu)化到為企業(yè)提供個(gè)性化軟件開(kāi)發(fā)等基于互聯(lián)網(wǎng)的全面整合營(yíng)銷(xiāo)服務(wù)。公司擁有豐富的網(wǎng)站建設(shè)和互聯(lián)網(wǎng)應(yīng)用系統(tǒng)開(kāi)發(fā)管理經(jīng)驗(yàn)、成熟的應(yīng)用系統(tǒng)解決方案、優(yōu)秀的網(wǎng)站開(kāi)發(fā)工程師團(tuán)隊(duì)及專(zhuān)業(yè)的網(wǎng)站設(shè)計(jì)師團(tuán)隊(duì)。
在StartUp.cs的Configure方法中添加
//為驗(yàn)證添加中間件
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
//驗(yàn)證方案名稱(chēng)
AuthenticationScheme = "loginvalidate",
//沒(méi)有權(quán)限時(shí)導(dǎo)航的登錄action
LoginPath = new Microsoft.AspNetCore.Http.PathString("/login"),
//訪(fǎng)問(wèn)被拒絕后的acion
AccessDeniedPath = new Microsoft.AspNetCore.Http.PathString("/Home/NoPermission"),
AutomaticAuthenticate = true,
AutomaticChallenge = true,
SlidingExpiration = true
});
HomeController中的登錄的action實(shí)現(xiàn)
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using System.Security.Claims;
namespace webAuth.Controllers
{
/// <summary>
/// 本Controller允許admin和user兩種角色可以訪(fǎng)問(wèn)
/// </summary>
[Authorize(Roles = "admin,user")]
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
/// <summary>
/// aobout只允許user角色訪(fǎng)問(wèn)
/// </summary>
/// <returns></returns>
[Authorize(Roles = "user")]
public IActionResult About()
{
var id = User.Claims.SingleOrDefault(c => c.Type == ClaimTypes.Sid).Value;
ViewData["Message"] = "UserID:"+ id;
return View();
}
/// <summary>
/// contact只允許admin角色訪(fǎng)問(wèn)
/// </summary>
/// <returns></returns>
[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();
}
/// <summary>
/// 允許所有登錄者
/// </summary>
/// <param name="returnUrl">如果用戶(hù)訪(fǎng)問(wèn)的不是登錄頁(yè),returnUrl將把這個(gè)url傳進(jìn)來(lái),待登錄成功后返回這個(gè)地址</param>
/// <returns></returns>
[AllowAnonymous]
[HttpGet("login")]
public IActionResult Login(string returnUrl)
{
//判斷是否驗(yàn)證
if (!HttpContext.User.Identity.IsAuthenticated)
{
//把返回地址保存在前臺(tái)的hide表單中
ViewBag.returnUrl = returnUrl;
}
ViewBag.error = null;
return View();
}
/// <summary>
/// 允許所有登錄者
/// </summary>
/// <param name="username">用戶(hù)名</param>
/// <param name="password">密碼</param>
/// <param name="returnUrl">返回u</param>
/// <returns></returns>
[AllowAnonymous]
[HttpPost("login")]
public IActionResult Login(string username, string password, string returnUrl)
{
//從數(shù)據(jù)庫(kù)驗(yàn)證用戶(hù),關(guān)取出用戶(hù)所需要信息
var users = new List<dynamic>() {
new { ID = 1, UserName = "zsf",Password="111", Name = "張三豐", RoleTypeID = 1, RoleType = "admin", RoleTypeName = "管理員" },
new { ID = 2, UserName = "zwj",Password="222", Name = "張無(wú)忌", RoleTypeID = 2, RoleType = "user", RoleTypeName = "普通用戶(hù)" }
};
var user = users.SingleOrDefault(u => u.UserName == username && u.Password == password);
if (user!=null)
{
//登錄成功后,設(shè)置聲明
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 = "用戶(hù)名或密碼錯(cuò)誤!";
return View();
}
}
}
}
Login.cshtml頁(yè)面如下:
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>登錄</title>
<link href="~/lib/bootstrap/dist/css/bootstrap.css" rel="stylesheet" />
<style>
.col-md-12 {
text-align: center;
margin-top: 10px;
}
.input-group {
width: 300px;
margin: 0 auto;
}
.input-group-addon{
width:80px;
}
</style>
</head>
<body>
<form method="post" action="/login">
<div class="container">
<div class="row" >
<div class="col-md-12">
<div class="input-group">
<span class="input-group-addon" id="basic-addon1">用戶(hù)名</span>
<input type="text" class="form-control" name="username" aria-describedby="basic-addon1">
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="input-group">
<span class="input-group-addon" id="basic-addon1">密碼</span>
<input type="password" class="form-control" name="password" aria-describedby="basic-addon1">
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="input-group" >
<input type="hidden" value="@ViewBag.returnUrl" name="returnUrl" />
<button type="submit" class="btn btn-primary" >登錄</button>
</div>
</div>
</div>
@if (ViewBag.error != null)
{
<font color="red">@ViewBag.error</font>
}
</div>
</form>
<script src="~/lib/bootstrap/dist/js/bootstrap.js"></script>
<script src="~/lib/jquery/dist/jquery.js"></script>
</body>
</html>如果在其他頁(yè)面使用User,可以像下面這樣使用
<span>當(dāng)前用戶(hù):@User.Identity.Name</span>
當(dāng)然也可以從User中查到其他登錄時(shí)存儲(chǔ)的Claim的值
登錄成功后
登錄成功后訪(fǎng)問(wèn)沒(méi)有權(quán)限頁(yè)面(當(dāng)然可以不讓這種角色看到不能訪(fǎng)問(wèn)的鏈接)

新聞名稱(chēng):asp.netcoreweb頁(yè)面驗(yàn)證
標(biāo)題來(lái)源:http://chinadenli.net/article8/phosop.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供、網(wǎng)站建設(shè)、域名注冊(cè)、小程序開(kāi)發(fā)、App設(shè)計(jì)、自適應(yīng)網(wǎng)站
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶(hù)投稿、用戶(hù)轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話(huà):028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)