分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 代码编程

.net core权限认证

发布时间:2023-09-06 02:03责任编辑:彭小芳关键词:暂无标签
在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.Namenew 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>


.net core权限认证

原文地址:http://blog.51cto.com/13717297/2140107

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved