新网创想网站建设,新征程启航

为企业提供网站建设、域名注册、服务器等服务

.netcore权限认证-创新互联

在Startup类中添加授权和验证的注入对象和中间件

创新互联公司长期为1000+客户提供的网站建设服务,团队从业经验10年,关注不同地域、不同群体,并针对不同对象提供差异化的产品和服务;打造开放共赢平台,与合作伙伴共同营造健康的互联网生态环境。为迁安企业提供专业的成都网站设计、成都做网站、外贸网站建设迁安网站改版等技术服务。拥有10多年丰富建站经验和众多成功案例,为您定制开发。

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();
	}

}

前台页面



	邮箱/用户名/手机号:
	
	
登录密码:
@ViewBag.error
记住密码

另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。


本文题目:.netcore权限认证-创新互联
路径分享:http://www.wjwzjz.com/article/cecicd.html

其他资讯

在线咨询
服务热线
服务热线:028-86922220
TOP