Example #1
0
        private async Task <OkObjectResult> GetClaimsIdentity(IAuthenticable user)
        {
            var identity = new ClaimsIdentity(new GenericIdentity(user.UserName, "Token"),
                                              new[]
            {
                new Claim("RoleId", user.Profile.Role.Id.ToString())
            });
            var role = "administrador";

            if (user.Profile.Role.Id == 3)
            {
                role = "resident";
            }
            if (user.Profile.Role.Id == 2)
            {
                role = "employee";
            }
            var claims = new[]
            {
                new Claim("UserName", user.UserName),
                new Claim("UserType", user.ToString()),
                new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
                new Claim(JwtRegisteredClaimNames.Jti, await _jwtOptions.JtiGenerator()),
                new Claim(JwtRegisteredClaimNames.Iat, ToUnixEpochDate(_jwtOptions.IssuedAt).ToString(), ClaimValueTypes.Integer64),
                identity.FindFirst("RoleId"),
                new Claim("roles", role)
            };

            // Create the JWT security token and encode it.
            var jwt = new JwtSecurityToken(
                issuer: _jwtOptions.Issuer,
                audience: _jwtOptions.Audience,
                claims: claims,
                notBefore: _jwtOptions.NotBefore,
                expires: _jwtOptions.Expiration,
                signingCredentials: _jwtOptions.SigningCredentials);

            var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);

            // Serialize and return the response
            var response = new Token
            {
                access_token = encodedJwt,
                expires_in   = (int)_jwtOptions.ValidFor.TotalSeconds
            };

            var json = JsonConvert.SerializeObject(response, _serializerSettings);

            _jwtFactory.JwtTokenLogSuccess(user, json);

            return(new OkObjectResult(json));
        }