標籤:cookie username task color identity ddc var mod state
首先在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
.net core 2.0 登陸許可權驗證