首先在Startup的ConfigureServices方法添加一段權限代碼
services.AddAuthentication(x=> {
x.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme; x.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme; x.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme; }).AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, x => { //登錄地址 x.LoginPath = "/Home/Login"; //sid x.Cookie.Name = "mycookie"; x.Cookie.Path = "/"; x.Cookie.HttpOnly = true; x.Cookie.Expiration = new TimeSpan(0, 0, 30); x.ExpireTimeSpan = new TimeSpan(0, 0, 30); });
這里整理下目錄。
有個HomeController,首頁的Index頁面添加[Authorize],需要權限進入
有個Login的action,登錄頁
添加登錄方法SignIn
public async Task<IActionResult> SignIn(LoginViewModel model)
{
if (ModelState.IsValid) { var claims = new List<Claim>(); claims.Add(new Claim(ClaimTypes.Name, model.UserName)); var identity = new ClaimsIdentity(claims, "login"); var principal = new ClaimsPrincipal(identity); await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal); if (principal.Identity.IsAuthenticated) return RedirectToAction("Index"); } return View(); }
添加登錄頁面
@{
ViewData["Title"] = "Login";
}
<h2>Login</h2>
<form method="post" action="/home/SignIn"> 用戶名<input type="text" name="username" /> 密碼<input type="password" name="password" /> <button type="submit" class="btn">登錄</button> </form>
因為在Startup里面配置了當沒權限時進入登錄頁面
x.LoginPath = "/Home/Login";
此時運行程序,會跳轉到登錄頁面
輸入用戶名密碼登陸,登錄驗證成功后就可以跳轉到Index了。
再添加個退出
public async Task<IActionResult> SignOut() { if (HttpContext.User.Identity.IsAuthenticated) await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); return RedirectToAction("Login"); }
在頁面上可以通過這段代碼判斷是否登錄
Context.User.Identity.IsAuthenticated