在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();
}
}前台页面