Ejemplo n.º 1
0
        public string GenerateToken(string userName, EUserRole userRole)
        {
            var now    = DateTime.UtcNow;
            var claims = new List <Claim>()
            {
                new Claim(ClaimsIdentity.DefaultNameClaimType, userName),
                new Claim(ClaimsIdentity.DefaultRoleClaimType, userRole.ToString()),
            };
            var identity = new ClaimsIdentity(claims, "Token");

            var token = new JwtSecurityToken(_opts.JwtIssuer,
                                             _opts.JwtAudience,
                                             identity.Claims,
                                             now,
                                             now.AddMinutes(_opts.JwtLifetimeMins),
                                             new SigningCredentials(_opts.PrivateKey, SecurityAlgorithms.RsaSha256));

            return(new JwtSecurityTokenHandler().WriteToken(token));
        }
Ejemplo n.º 2
0
 /// <summary>
 /// Check if the authorization header has a specific role
 /// </summary>
 /// <param name="role"></param>
 /// <returns></returns>
 public AmazingRequestContext HasRole(EUserRole role)
 {
     if (this.Claims.FirstOrDefault(claim => claim.Type == ClaimTypes.Role)?.Value != role.ToString())
     {
         throw new AmazingException(HttpStatusCode.Unauthorized, $"Unauthorized");
     }
     return(this);
 }