ASP.NET Core中的授权(2) — 基于声明

2019-08-10  本文已影响0人  谁有羊毛

程序认证身份之后就是授权,授权也有很多种

三种:基于角色, 基于声明,基于策略

此次授权的demo之git地址:https://github.com/xeekseven/AspNet-core-Example/tree/master/ANC-Authorize-Policy

基于声明:(用此可以替代基于角色了)

其实这个有点像自由版 基于角色 授权。其中的判断逻辑运算还是 equal,但是type和值都可以自己定义

  1. 首先启用服务
services.AddAuthorization(options =>
{
    //声明一个名为Administrator的授权,判断角色的claimType为Role的值是否equal Administrator
    options.AddPolicy("Administrator", policy => policy.RequireClaim("Role","Administrator"));
});
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
    options.AccessDeniedPath = new PathString("/Home/NotPermission");
    options.LoginPath = new PathString("/Home/Login");
    options.ExpireTimeSpan = TimeSpan.FromSeconds(10);
});

可以看到 添加了一个Type为Role的声明,然后又认证失败时候重定向路径

options.LoginPath = new PathString("/Admin/Login");

然后也添加了一个无权限时的重定向路径

options.AccessDeniedPath = new PathString("/Home/NotPermission");
  1. 然后配置HTTP请求管道:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
    }

    app.UseStaticFiles(); 
    app.UseAuthentication();
    app.UseRouting();
    app.UseAuthorization();
    app.UseCookiePolicy();

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });
}

以上就是配置了

  1. 首先是登录,
[HttpPost]
[AllowAnonymous]
public async Task<IActionResult> Login(string username,string password)
{
    var returnUrl = HttpContext.Request.Query["ReturnUrl"];
    string roleType = "";
    if(username == "admin"){
        roleType =  "Administrator";
    }
    else if(username == "custom"){
        roleType = "Custom";
    }
    if((username == "admin" && password == "admin") || (username == "custom" && password == "custom")){
        var claims = new List<Claim>
        {
            new Claim(ClaimTypes.Name,username),
            new Claim("Role",roleType)
        };
        var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
        await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, 
        new ClaimsPrincipal(claimsIdentity), new AuthenticationProperties());
        
        if (!string.IsNullOrWhiteSpace(returnUrl))
        {
            return Redirect(returnUrl);
        }
        return Redirect("/Home/Index");
    }
    if (!string.IsNullOrWhiteSpace(returnUrl))
    {
        return Redirect(returnUrl);
    }
    return Redirect("/Home/Login");
}
  1. 接下来就是使用声明来进行鉴权了。在需要鉴权的接口加上特性并指定特定的声明即可,没有权限的(Role的对应的值 !=Administrator)就会重定向到 "/Home/NotPermission"(options.AccessDeniedPath = new PathString("/Home/NotPermission");)
[Authorize(Policy="Administrator")]
public IActionResult Privacy()
{
    return View();
}
  1. 总结就是:

前一篇 — ASP.NET Core中的授权(1) — 基于角色:https://www.jianshu.com/p/a8e663627ec9

下一篇 — ASP.NET Core中的授权(3) — 基于自定义策略:https://www.jianshu.com/p/0bdf572cc103

上一篇下一篇

猜你喜欢

热点阅读