您的位置:首页 > 编程语言 > ASP

Asp.Net Core 2.0 多角色权限认证

2017-10-10 00:00 597 查看
在使用 WebForm 技术开发网站的时候,微软就提供了 Form 身份认证,这使得登录认证简单了许多,不同于 WebForm 以及后来的 Asp.Net Mvc,Asp.Net Core 中的身份认证与之前相比使用更加便捷,本文介绍 Asp.Net Core 2.0 多角色授权认证,首先我们需要在 Startup.cs 中开启授权认证相关模块(中间件),代码如下:
services.AddAuthentication(
   options=>
   {
       options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
       options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
   })
.AddCookie(options =>
   {
       options.LoginPath = "/Account/";
       options.Cookie.HttpOnly = true;
   });
services.AddTransient<HttpContextAccessor>();

app.UseAuthentication();


之后,我们在登录模块编写多角色登录逻辑代码如下:
[HttpPost]
public async Task<IActionResult> Login(string userCode, string userPassword, int userType = 0, string returnUrl = "")
{
   if ((userCode.Trim().ToLower() == "admin" || userCode.Trim().ToLower() == "user") && userPassword.Trim().ToLower() == "123456")
   {
       var claimsIdentity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
       claimsIdentity.AddClaim(new Claim(ClaimTypes.Sid, userCode));
       if (userType == RoleTypeEnum.UserType_Admin)
       {
           claimsIdentity.AddClaim(new Claim(ClaimTypes.Role, RoleTypeEnum.Admin));
       }
       else
       {
           claimsIdentity.AddClaim(new Claim(ClaimTypes.Role, RoleTypeEnum.User));
       }

       var claimsPrincipal = new ClaimsPrincipal(claimsIdentity);
       await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, claimsPrincipal, new AuthenticationProperties
       {
           ExpiresUtc = DateTime.UtcNow.AddMinutes(20)
       });

       if (!string.IsNullOrEmpty(returnUrl))
       {
           return this.Redirect(returnUrl);
       }
       else
       {
           if (userType == RoleTypeEnum.UserType_Admin)
           {
               return this.Redirect(Url.Action("Index", "Home", new { area = "Admin" }));
           }
           else
           {
               return this.Redirect(Url.Action("Index", "Home", new { area = "User" }));
           }
       }
   }
   else
   {
       return this.Content(string.Format("<script>alert('用户名或者密码错误');location.href='{0}'</script>", Url.Action("Index", "Account")), "text/html;charset=utf8");
   }
}


本例只提供管理和普通用户两种角色类别,可以根据情况自由添加,接着,我们就可以在相关授权模块添加 Authorize 元属性来进行角色授权,代码如下:
// 管理员模块
[Authorize(Roles = RoleTypeEnum.Authorize_Admin)]
[Area("Admin")]
public class BaseController : Controller
{
   protected string userCode;

   public BaseController(IHttpContextAccessor contextAccessor)
   {
       this.userCode = contextAccessor.HttpContext.User.FindFirst(ClaimTypes.Sid).Value;
   }

   protected void InitCookieViewData()
   {
       ViewData.Add("UserCode", this.userCode);
   }
}
// 用户模块
[Authorize(Roles = RoleTypeEnum.Authorize_User)]
[Area("User")]
public class BaseController : Controller
{
   protected string userCode;

   public BaseController(IHttpContextAccessor contextAccessor)
   {
       this.userCode = contextAccessor.HttpContext.User.FindFirst(ClaimTypes.Sid).Value;
   }

   protected void InitCookieViewData()
   {
       ViewData.Add("UserCode", this.userCode);
   }
}


到此,多角色授权认证已经结束,而且我们也获得了登录的角色信息,退出登录的代码如下:
public async Task<IActionResult> Logout()
{
   await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
   return this.Redirect(Url.Action("Index", "Account", new { area = "" }));
}


本文已提供案例下载地址。
原文地址:https://www.liziwu.net/topic/31.html
.NET社区新闻,深度好文,微信中搜索dotNET跨平台或扫描二维码关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: