Session + Cookie 鉴权、授权
一、配置及登录权授
1、Program.cs配置
//配置鉴权 builder.Services.AddAuthentication(option => { option.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme; option.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme; option.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme; option.DefaultSignOutScheme = CookieAuthenticationDefaults.AuthenticationScheme; option.DefaultForbidScheme = CookieAuthenticationDefaults.AuthenticationScheme; }).AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, option => { option.LoginPath = "/User/Login"; //如果用户没有登录或过期,则跳转到这边
option.AccessDeniedPath = "/User/NoAuthority"; //没有权限跳转的页面
});
app.UseAuthentication(); //鉴权 app.UseAuthorization(); //授权
2、创建UserController
1 using Microsoft.AspNetCore.Authentication; 2 using Microsoft.AspNetCore.Authentication.Cookies; 3 using Microsoft.AspNetCore.Authorization; 4 using Microsoft.AspNetCore.Mvc; 5 using System.Security.Claims; 6 7 namespace Project6.Controllers 8 { 9 public class UserController : Controller 10 { 11 [Authorize] 12 public IActionResult Index() 13 { 14 return View(); 15 } 16 17 [HttpGet] 18 public IActionResult Login() 19 { 20 return View(); 21 } 22 23 [HttpPost] 24 public async Task<IActionResult> Login(string name,string password) 25 { 26 if("ziff".Equals(name) && "1".Equals(password)) 27 { 28 var claims = new List<Claim>() 29 { 30 new Claim("Userid","1"), 31 new Claim(ClaimTypes.Role,"Admin"), 32 new Claim(ClaimTypes.Name,name), 33 new Claim(ClaimTypes.Email,"123@qq.com"), 34 new Claim("password",password), 35 new Claim("account","Administrator"), 36 new Claim("role","admin") 37 }; 38 ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(new ClaimsIdentity(claims,"Customer")); 39 HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,claimsPrincipal,new AuthenticationProperties() 40 { 41 ExpiresUtc = DateTime.UtcNow.AddMinutes(30), 42 }).Wait(); 43 var user = HttpContext.User; 44 return base.Redirect("/User/Index"); 45 } 46 else 47 { 48 base.ViewBag.Msg = "用户密码错误"; 49 return base.Redirect("/User/Login"); 50 } 51 52 } 53 } 54 }
3、创建类UserInfo
1 namespace Project6.Model 2 { 3 public class UserInfo 4 { 5 public string Name { get; set; } 6 public string Password { get; set; } 7 8 } 9 }
4、创建Index.cshtml视图
<h1>
登录后才能看到这个信息
</h1>
5、创建Login视图
1 @using Project6.Model 2 @model UserInfo 3 <div> 4 <section> 5 @using (Html.BeginForm("Login", "User", new { sid = "123", Account = "ziff" },FormMethod.Post,true,new { @class = "form-horizontal",role="form"})) 6 { 7 @Html.AntiForgeryToken() 8 <hr /> 9 @Html.ValidationSummary(true) 10 <div> 11 @Html.LabelFor(m=>m.Name) 12 <div> 13 @Html.TextBoxFor(m=>m.Name) 14 </div> 15 </div> 16 <div> 17 @Html.LabelFor(m=>m.Password) 18 <div> 19 @Html.PasswordFor(m=>m.Password) 20 </div> 21 </div> 22 <div> 23 <button type="submit">登录</button> 24 @base.ViewBag.Msg 25 </div> 26 } 27 </section> 28 </div>
二、角色授权及策略授权
1、在Program.cs配置策略授权
1 { 2 builder.Services.AddAuthorization(options => 3 { 4 options.AddPolicy("rolePolicy", policyBuilder => 5 { 6 policyBuilder.RequireRole("Admin"); //需要Admin权限 7 8 }); 9 options.AddPolicy("accountPolicy", policyBuilder => 10 { 11 policyBuilder.RequireClaim("account", new string[] { "Administrator","Test" }); //需要Administrator或Test至少一个权限 12 }); 13 options.AddPolicy("rolePolicy2", policyBuilder => 14 { 15 policyBuilder.RequireAssertion(context => 16 { 17 return context.User.HasClaim(c => c.Type == ClaimTypes.Role) 18 && context.User.Claims.First(c => c.Type.Equals(ClaimTypes.Role)).Value == "Admin"; 19 }); 20 }); 21 }); 22 }
2、角色判断主要在通过Roles判断
[Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme,Roles = "Admin")]
策略权限通过Policy判断
[Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme, Policy = "rolePolicy")]
重新写UserController进行验证
1 using Microsoft.AspNetCore.Authentication; 2 using Microsoft.AspNetCore.Authentication.Cookies; 3 using Microsoft.AspNetCore.Authorization; 4 using Microsoft.AspNetCore.Mvc; 5 using System.Security.Claims; 6 7 namespace Project6.Controllers 8 { 9 public class UserController : Controller 10 { 11 /// <summary> 12 /// 用户是Admin角色才能访问 13 /// </summary> 14 /// <returns></returns> 15 [Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme,Roles = "Admin")] 16 public IActionResult Index() 17 { 18 return View(); 19 } 20 /// <summary> 21 /// 用户是Manage角色才能访问 22 /// </summary> 23 /// <returns></returns> 24 [Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme, Roles = "Manage")] 25 public IActionResult Index2() 26 { 27 return View(); 28 } 29 30 /// <summary> 31 /// Admin、User都有才能访问 32 /// </summary> 33 /// <returns></returns> 34 [Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme, Roles = "Admin")] 35 [Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme, Roles = "User")] 36 public IActionResult Index3() 37 { 38 return View(); 39 } 40 41 /// <summary> 42 /// 有Admin,User其中一个权限可以访问 43 /// </summary> 44 /// <returns></returns> 45 [Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme, Roles = "Admin,User")] 46 public IActionResult Index4() 47 { 48 return View(); 49 } 50 /// <summary> 51 /// 没Admin、User、Manage都有才能访问 52 /// </summary> 53 /// <returns></returns> 54 [Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme, Roles = "Admin")] 55 [Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme, Roles = "User")] 56 [Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme, Roles = "Manage")] 57 public IActionResult Index5() 58 { 59 return View(); 60 } 61 /// <summary> 62 /// 有Admin,Manage其中一个权限才能访问 63 /// </summary> 64 /// <returns></returns> 65 [Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme, Roles = "Admin,Manage")] 66 public IActionResult Index6() 67 { 68 return View(); 69 } 70 /// <summary> 71 /// 符合策略rolePolicy才能访问 72 /// </summary> 73 /// <returns></returns> 74 [Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme, Policy = "rolePolicy")] 75 public IActionResult Index7() 76 { 77 return View(); 78 } 79 /// <summary> 80 /// 符合策略accountPolicy才能访问 81 /// </summary> 82 /// <returns></returns> 83 [Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme, Policy = "accountPolicy")] 84 public IActionResult Index8() 85 { 86 return View(); 87 } 88 89 [HttpGet] 90 public IActionResult Login() 91 { 92 return View(); 93 } 94 95 [HttpPost] 96 public async Task<IActionResult> Login(string name,string password) 97 { 98 if("ziff".Equals(name) && "1".Equals(password)) 99 { 100 var claims = new List<Claim>() 101 { 102 new Claim("Userid","1"), 103 new Claim(ClaimTypes.Role,"Admin"), 104 //new Claim(ClaimTypes.Role,"User"), 105 new Claim(ClaimTypes.Name,name), 106 new Claim(ClaimTypes.Email,"123@qq.com"), 107 new Claim("password",password), 108 new Claim("account","Administrator"), 109 new Claim("role","admin") 110 }; 111 ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(new ClaimsIdentity(claims,"Customer")); 112 HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,claimsPrincipal,new AuthenticationProperties() 113 { 114 ExpiresUtc = DateTime.UtcNow.AddMinutes(30), 115 }).Wait(); 116 var user = HttpContext.User; 117 return base.Redirect("/User/Index"); 118 } 119 else 120 { 121 base.ViewBag.Msg = "用户密码错误"; 122 return base.Redirect("/User/Login"); 123 } 124 125 } 126 127 public IActionResult NoAuthority() 128 { 129 return View(); 130 } 131 } 132 }
三、通过业务逻辑判断权限
1、增加业务逻辑层Services
增加文件IUserService.cs
namespace Services { public interface IUserService { public bool Validate(string userId, string qq); } }
增加文件UserService.cs
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace Services 8 { 9 public class UserService : IUserService 10 { 11 public bool Validate(string userId, string qq) 12 { 13 return userId == "1" && qq == "123456"; 14 } 15 } 16 }
2、增加判断handler
QQEmailRequirement.cs
1 using Microsoft.AspNetCore.Authorization; 2 3 namespace Project6.Utility 4 { 5 public class QQEmailRequirement :IAuthorizationRequirement 6 { 7 8 } 9 }
QQHandler.cs
1 using Microsoft.AspNetCore.Authorization; 2 using Services; 3 4 namespace Project6.Utility 5 { 6 public class QQHandler : AuthorizationHandler<QQEmailRequirement> 7 { 8 private IUserService _UserService; 9 10 public QQHandler(IUserService userService) 11 { 12 this._UserService = userService; 13 } 14 15 /// <summary> 16 /// 判断是否授权 17 /// </summary> 18 /// <param name="context"></param> 19 /// <param name="requirement"></param> 20 /// <returns></returns> 21 protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, QQEmailRequirement requirement) 22 { 23 try 24 { 25 string userId = context.User.Claims.First(c => c.Type == "Userid").Value; 26 string qq = context.User.Claims.First(c => c.Type == "qq").Value.Trim(); 27 28 if (_UserService.Validate(userId, qq)) 29 { 30 context.Succeed(requirement); //验证通过 31 } 32 else 33 { 34 context.Fail(); //验证不通过 35 } 36 } 37 catch (Exception ex) 38 { 39 context.Fail(); 40 } 41 42 return Task.CompletedTask; 43 } 44 } 45 }
3、Program.cs增加策略
1 options.AddPolicy("rolePolicy2", policyBuilder => 2 { 3 policyBuilder.RequireAssertion(context => 4 { 5 return context.User.HasClaim(c => c.Type == ClaimTypes.Role) 6 && context.User.Claims.First(c => c.Type.Equals(ClaimTypes.Role)).Value == "Admin" 7 && context.User.Claims.Any(c=>c.Type == ClaimTypes.Name); 8 }); 9 10 policyBuilder.AddRequirements(new QQEmailRequirement()); 11 });
IOC注册
1 builder.Services.AddTransient<IUserService, UserService>(); //控制反转注册 2 builder.Services.AddTransient<IAuthorizationHandler, QQHandler>();//控制反转注册
4、UserController.cs添加策略验证
1 [Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme, Policy = "rolePolicy2")] 2 public IActionResult Index9() 3 { 4 return View(); 5 }