ASP.NET Core中的授权(1) — 基于角色

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

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

基于角色:

a)这个目前系统有默认Role的Type —— ClaimTypes.Role,
b)主要实现的逻辑就是 去比对 Claim 这个实例中的ClaimTypes.Role属性的值 是否 与 [Authorize(Roles = "Administrator")] 中 Roles的值是否一致

实现方式
  1. 配置Startup.cs 类,使用Cookie及角色授权方式访问 —— 修改 ConfigureServices 与 Configure方法
public class Startup
{
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //***********1. 添加验证和授权中间件************************************************
            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(options =>
            {
                options.AccessDeniedPath = new PathString("/Home/NotPermission");
                options.LoginPath = new PathString("/Home/Login");
                options.ExpireTimeSpan = TimeSpan.FromSeconds(10);
            });
            services.AddAuthorization();
           // **************************************************************************************
            services.AddControllersWithViews();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }
            app.UseStaticFiles();

            app.UseRouting();
           // ********2 . 添加验证和授权********************************************************
            app.UseAuthentication();
            app.UseAuthorization();
          // **************************************************************************************

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
}
  1. 使用的时候在Authorize特性上赋值上Role属性值, 表示该方法只能由Administrator的角色访问
// 表示 ClaimTypes.Role 的值为 Administrator 的才可以访问
[Authorize(Roles = "Administrator")]
public IActionResult Privacy()
{
     return View();
}
  1. 登陆代码,登陆成功后设置 Claim 的 ClaimTypes.Role 为对应的角色
[HttpPost]
[AllowAnonymous]
public async Task 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
        {
            new Claim(ClaimTypes.Name,username),
            new Claim(ClaimTypes.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");
}

下一篇 —ASP.NET Core中的授权(2) — 基于声明: https://www.jianshu.com/p/f96c181c34d9

你可能感兴趣的:(ASP.NET Core中的授权(1) — 基于角色)