Search code examples
asp.netasp.net-coreasp.net-authorization

how to tell services.AddAuthorization where is my custom user and role table is


I just build my user and role policy table and a table for connecting these to gather but how to tell services.AddAuthorization to looking for which policy in which table.

I had read the document of Microsoft Role-based authorization but they don't use custom user and role table I even don't know how to ask my question I confused

I mean how did it know were looking for Administrator in this picture enter image description here


Solution

  • I just build my user and role policy table and a table for connecting these to gather but how to tell services.AddAuthorization to looking for which policy in which table.

    By default, in the official Microsoft document (about Role-based or Policy-based authorization), it uses the Asp.net core Identity to manage the user and role.

    From you description, I assume you also use the Asp.net Identity page to login and logout, right? If that is the case, since you are using a custom user and role table, in the Login.cshtml.cs file, after user login successfully, you could query this table based on the login user's email and get the user's role. Then add the role claims to the current user. After that, you can create policy based on the claims.

    You can check the following sample code:

    In the Login.cshtml.cs page:

    var result = await _signInManager.PasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure: false);
    if (result.Succeeded)
    {
        //find current user.
        var user = await _userManager.FindByEmailAsync(Input.Email);
        //based on user information to query the user and role policy table. Here I set the user role directly.
        var userrole = "User";
        if (user.UserName.Contains("aa"))
        { 
            userrole = "Admin";
        }
    
        //add claims to current user. 
        await _userManager.AddClaimAsync(user, new Claim(ClaimTypes.Role, userrole));
        var claimsPrincipal = await _signInManager.CreateUserPrincipalAsync(user);
        await _signInManager.RefreshSignInAsync(user);
    
        _logger.LogInformation("User logged in.");
        return LocalRedirect(returnUrl);
    }
    

    In the ConfigureServices method, create a policy based on the claims.

    services.AddAuthorization(options =>
    {
        options.AddPolicy("RequiredAdmin", policy =>
            policy.RequireClaim(ClaimTypes.Role, "Admin"));
    });
    

    Then, in the Configure method, add the following code:

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

    and apply the policy to the action method:

        [Authorize(Policy = "RequiredAdmin")]
        public IActionResult Privacy()
        { 
            return View();
        }
    

    The result as below: The User aa is Admin role, and the bb is User role.

    enter image description here

    Besides, here are some relate articles, you can refer them:

    Policy-based authorization in ASP.NET Core

    Policy-Based And Role-Based Authorization In ASP.NET Core 3.0 Using Custom Handler

    Cookie Authentication In ASP.NET Core(if you don't use Asp.net core Identity, you can refer this article and configure the policy).