.net core 2.0 登陸權限驗證


首先在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

 


免責聲明!

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



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