您好,登錄后才能下訂單哦!
在Startup類中添加授權和驗證的注入對象和中間件
1.在ConfigureServices方法注入對象
//驗證注入 services.AddAuthentication ( opts=>opts.DefaultScheme= Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationDefaults.AuthenticationScheme ).AddCookie( Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationDefaults.AuthenticationScheme , opt => { opt.LoginPath = new Microsoft.AspNetCore.Http.PathString("/login"); opt.AccessDeniedPath= new Microsoft.AspNetCore.Http.PathString("/home/error"); opt.LogoutPath= new Microsoft.AspNetCore.Http.PathString("/login"); opt.Cookie.Path = "/"; } );
2.在Configure方法中添加中間件
//開啟驗證中間件 app.UseAuthentication();
在特效下去授權controller和action
[Authorize(Roles ="admin")]//允許那些角色訪問 [AllowAnonymous]//允許所有人訪問
登錄方法
[HttpGet("login")] [AllowAnonymous]//允許所有人訪問 public IActionResult Login( string returnUrl) { //沒有通過驗證 if ( ! HttpContext.User.Identity.IsAuthenticated) { ViewBag.returnUrl = returnUrl; } return View(); }
登錄實現功能方法
[HttpPost("login")] [AllowAnonymous]//允許所有人訪問 public IActionResult Login(string NET_User, string PassWord ,string returnUrl) { if (NET_User == "123" && PassWord == "123") { var claims = new System.Security.Claims.Claim[] { new System.Security.Claims.Claim(System.Security.Claims.ClaimTypes.Role,"admin"), //User.Identity.Name new System.Security.Claims.Claim(System.Security.Claims.ClaimTypes.Name,"NAME"), }; HttpContext.SignInAsync( Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationDefaults.AuthenticationScheme, new System.Security.Claims.ClaimsPrincipal(new System.Security.Claims.ClaimsIdentity(claims)) ); return new RedirectResult(string.IsNullOrEmpty(returnUrl) ? "/home/index":returnUrl); } else { ViewBag.error = "用戶名或密碼錯誤"; return View(); } }
前臺頁面
<form method="post" action="login" class="am-form"> <label for="email">郵箱/用戶名/手機號:</label> <input type="text" name="NET_User" value=""> <br> <label for="password">登錄密碼:</label> <input type="password" name="PassWord" value=""> <input type="hidden" name="returnUrl" value="@ViewBag.returnUrl"> <br> <span style="color:red">@ViewBag.error</span> <br> <label for="remember-me"> <input id="remember-me" type="checkbox"> 記住密碼 </label> <br /> <div class="am-cf"> <input type="submit" name="" value="登 錄" class="am-btn am-btn-primary am-btn-sm am-fl"> <input type="submit" name="" value="忘記密碼 ^_^? " class="am-btn am-btn-default am-btn-sm am-fr"> </div> </form>
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。