opts.DefaultScheme= ..."/>
您好,登錄后才能下訂單哦!
在Startup類中添加授權(quán)和驗(yàn)證的注入對(duì)象和中間件
1.在ConfigureServices方法注入對(duì)象
//驗(yàn)證注入 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方法中添加中間件
//開啟驗(yàn)證中間件 app.UseAuthentication();
在特效下去授權(quán)controller和action
[Authorize(Roles ="admin")]//允許那些角色訪問 [AllowAnonymous]//允許所有人訪問
登錄方法
[HttpGet("login")] [AllowAnonymous]//允許所有人訪問 public IActionResult Login( string returnUrl) { //沒有通過驗(yàn)證 if ( ! HttpContext.User.Identity.IsAuthenticated) { ViewBag.returnUrl = returnUrl; } return View(); }
登錄實(shí)現(xiàn)功能方法
[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 = "用戶名或密碼錯(cuò)誤"; return View(); } }
前臺(tái)頁面
<form method="post" action="login" class="am-form"> <label for="email">郵箱/用戶名/手機(jī)號(hào):</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>
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。