簡體   English   中英

基於自定義角色的身份驗證 .NET CORE

[英]Custom role based auth .NET CORE

我有一個項目,其中用戶可以有多個角色,例如收銀員和存貨員。 這些角色具有相同的權限,但有人也可以擁有 admin 和 cashier 角色。 在這種情況下,他可以訪問比管理員/收銀員更多的功能。

我已經進行了廣泛的搜索,但我沒有從文檔中得到任何更明智的信息,因為我最初認為政策是可行的方法,但現在我認為我們需要基於聲明的授權。

在搜索和玩耍后,我沒有找到以下問題的答案:

  1. 我需要哪些表/實體?
  2. 這可以在沒有腳手架工具的情況下完成嗎?
  3. 這整個過程是如何工作的,.NET CORE 如何知道要查看哪些角色? 如何使用自定義角色?

如果有人能幫我解決這個問題,我將不勝感激。

干杯。

一種方法是使用 Identity 並使用[Authorize(Roles ="Admin")]授權用戶。

如果你不想使用腳手架工具,你可以使用 jwt 令牌認證或 cookie 認證。

下面是一個關於如何使用 cookie 身份驗證的簡單演示:

模型:

public class User
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Password { get; set; }
    public List<UserRole> UserRoles { get; set; }
}
public class Role
{
    public int Id { get; set; }
    public string RoleName { get; set; }
    public List<UserRole> UserRoles { get; set; }
}
public class UserRole
{
    public int UserId { get; set; }
    public User User { get; set; }
    public int RoleId { get; set; }
    public Role Role { get; set; }
}
public class LoginModel
{
    public string Name { get; set; }
    public string Password { get; set; }
}

控制器:

public class HomeController : Controller
{
    private readonly YouDbContext _context;

    public HomeController(YouDbContext context)
    {
        _context = context;
    }
    public IActionResult Login()
    {
        return View();
    }
    [HttpPost]
    public async Task<IActionResult> Login(LoginModel model)
    {
        var claims = new List<Claim>{};
        var user = _context.User
                           .Include(u=>u.UserRoles)
                           .ThenInclude(ur=>ur.Role)
                           .Where(m => m.Name == model.Name).FirstOrDefault();
        if(user.Password==model.Password)
        {
            foreach(var role in user.UserRoles.Select(a=>a.Role.RoleName))
            {
                var claim = new Claim(ClaimTypes.Role, role);
                claims.Add(claim);
            }               
            var claimsIdentity = new ClaimsIdentity(
                claims, CookieAuthenticationDefaults.AuthenticationScheme);

            var authProperties = new AuthenticationProperties{};
            await HttpContext.SignInAsync(
                CookieAuthenticationDefaults.AuthenticationScheme,
                new ClaimsPrincipal(claimsIdentity),
                authProperties);
        }
        return View("Index");
    }       
    public IActionResult Index()
    {
        return View();
    }

    //allow Cashier
    [Authorize(Roles = "Cashier")]
    public IActionResult Privacy()
    {
        return View();
    }

    //allow Admin
    [Authorize(Roles = "Admin")]
    public IActionResult AllowAdmin()
    {
        return View();
    }

    //allow both of the Admin and Cashier
    [Authorize(Roles = "Admin,Cashier")]
    public IActionResult AllowBoth()
    {
        return View();
    }

    //user has no rights to access the page
    public IActionResult AccessDenied()
    {
        return View();
    }

    //log out
    public async Task<IActionResult> Logout()
    {
        await HttpContext.SignOutAsync(
CookieAuthenticationDefaults.AuthenticationScheme);
        return RedirectToAction("Index");
    }        
}

數據庫上下文:

public class YouDbContext: DbContext
{
    public YouDbContext(DbContextOptions<YouDbContext> options)
        : base(options)
    {
    }

    public DbSet<User> User { get; set; }
    public DbSet<Role> Role { get; set; }
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<UserRole>()
   .HasKey(bc => new { bc.UserId, bc.RoleId });
        modelBuilder.Entity<UserRole>()
            .HasOne(bc => bc.User)
            .WithMany(b => b.UserRoles)
            .HasForeignKey(bc => bc.UserId);
        modelBuilder.Entity<UserRole>()
            .HasOne(bc => bc.Role)
            .WithMany(c => c.UserRoles)
            .HasForeignKey(bc => bc.RoleId);
    }
}

啟動.cs:

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllersWithViews();
        services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                .AddCookie(options =>
                {
                    options.LoginPath = "/Home/Login";
                    options.AccessDeniedPath = "/Home/AccessDenied";
                });
        services.AddDbContext<WebApplication1Context>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("WebApplication1Context")));
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseHttpsRedirection();
        app.UseStaticFiles();

        app.UseRouting();

        app.UseAuthentication();
        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
        });
    }
}

結果:

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM