Skip to content

Instantly share code, notes, and snippets.

@xiaomi7732
Last active September 22, 2022 01:02
Show Gist options
  • Save xiaomi7732/4dc8a6d6b0c971b82ab96810e637b446 to your computer and use it in GitHub Desktop.
Save xiaomi7732/4dc8a6d6b0c971b82ab96810e637b446 to your computer and use it in GitHub Desktop.

JWT Multiple Roles Cheatsheet

Put multiple roles to the JWT token claims:

// Package: System.IdentityModel.Tokens.Jwt
JwtSecurityToken token = new JwtSecurityToken(
    issuer: "saar",
    audience: "saar-audience",
    claims: new[] {
        new Claim(ClaimTypes.Role, "Admin") // Usually getting roles from database for the current user
        new Claim(ClaimTypes.Role, "User")  // Now, the second role for user.
    },
    expires: DateTime.UtcNow.AddMinutes(5),
    signingCredentials: new SigningCredentials(
        key: new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Secret)),
        algorithm: SecurityAlgorithms.HmacSha256
    )
);

Authorization

To allow either role to access the resource:

public class ProtectedResourceController : ControllerBase
{
    [Route("protectedInfo")]
    [HttpGet]
    // Allows either User or Admin access.
    [Authorize(Roles = "User, Admin")]
    public IActionResult Get()
    {
        return Ok("You can see this message means you are a valid user.");
    }
}

To require both roles to access the resource:

public class ProtectedResourceController : ControllerBase
{
    [Route("protectedInfo")]
    [HttpGet]
    // Only accepts claims having both Admin and User
    [Authorize(Roles = "Admin")]
    [Authorize(Roles = "User")]
    public IActionResult Get()
    {
        return Ok("You can see this message means you are a valid user.");
    }
}

Video

Reference

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment