.net core权限认证
在Startup类中添加授权和验证的注入对象和中间件
1.在ConfigureServices方法注入对象
//验证注入services.AddAuthentication(opts=>opts.DefaultScheme=Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationDefaults.AuthenticationScheme,opt=>{opt.LoginPath=newMicrosoft.AspNetCore.Http.PathString("/login");opt.AccessDeniedPath=newMicrosoft.AspNetCore.Http.PathString("/home/error");opt.LogoutPath=newMicrosoft.AspNetCore.Http.PathString("/login");opt.Cookie.Path="/";});
2.在Configure方法中添加中间件
//开启验证中间件app.UseAuthentication();
在特效下去授权controller和action
[Authorize(Roles="admin")]//允许那些角色访问[AllowAnonymous]//允许所有人访问
登录方法
[HttpGet("login")][AllowAnonymous]//允许所有人访问publicIActionResultLogin(stringreturnUrl){//没有通过验证if(!HttpContext.User.Identity.IsAuthenticated){ViewBag.returnUrl=returnUrl;}returnView();}
登录实现功能方法
[HttpPost("login")][AllowAnonymous]//允许所有人访问publicIActionResultLogin(stringNET_User,stringPassWord,stringreturnUrl){if(NET_User=="123"&&PassWord=="123"){varclaims=newSystem.Security.Claims.Claim[]{newSystem.Security.Claims.Claim(System.Security.Claims.ClaimTypes.Role,"admin"),//User.Identity.NamenewSystem.Security.Claims.Claim(System.Security.Claims.ClaimTypes.Name,"NAME"),};HttpContext.SignInAsync(Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationDefaults.AuthenticationScheme,newSystem.Security.Claims.ClaimsPrincipal(newSystem.Security.Claims.ClaimsIdentity(claims)));returnnewRedirectResult(string.IsNullOrEmpty(returnUrl)?"/home/index":returnUrl);}else{ViewBag.error="用户名或密码错误";returnView();}}
前台页面
<formmethod="post"action="login"class="am-form"><labelfor="email">邮箱/用户名/手机号:</label><inputtype="text"name="NET_User"value=""><br><labelfor="password">登录密码:</label><inputtype="password"name="PassWord"value=""><inputtype="hidden"name="returnUrl"value="@ViewBag.returnUrl"><br><spanstyle="color:red">@ViewBag.error</span><br><labelfor="remember-me"><inputid="remember-me"type="checkbox">记住密码</label><br/><divclass="am-cf"><inputtype="submit"name=""value="登录"class="am-btnam-btn-primaryam-btn-smam-fl"><inputtype="submit"name=""value="忘记密码^_^?"class="am-btnam-btn-defaultam-btn-smam-fr"></div></form>
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。