public string GerarToken(UsuarioRoot usuario)
        {
            var tokenHandler = new JwtSecurityTokenHandler();

            var jwtSettings = configuration["AuthSettings:JwtSecret"];
            var key         = Encoding.ASCII.GetBytes(jwtSettings);

            var expirationDays = Convert.ToInt32(configuration["AuthSettings:JwtExpirationDays"]);

            var claims = new List <Claim>
            {
                new Claim(ClaimTypes.Name, usuario.Id.ToString()),
                new Claim(JwtRegisteredClaimNames.Sub, usuario.Login),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                new Claim(JwtRegisteredClaimNames.Aud, configuration["AuthSettings:JwtAudience"]),
                new Claim(JwtRegisteredClaimNames.Iss, configuration["AuthSettings:JwtIssuer"]),
                new Claim(JwtRegisteredClaimNames.NameId, usuario.Id.ToString()),
            };

            foreach (var role in usuario.RolesUsuario)
            {
                claims.Add(new Claim(ClaimsIdentity.DefaultRoleClaimType, role.RoleId.ToString()));
            }

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject            = new ClaimsIdentity(claims),
                Expires            = DateTime.UtcNow.AddDays(expirationDays),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key),
                                                            SecurityAlgorithms.HmacSha256Signature)
            };

            var token = tokenHandler.CreateToken(tokenDescriptor);

            return(tokenHandler.WriteToken(token));
        }
Esempio n. 2
0
        public string SignIn(UsuarioRoot usuario)
        {
            var token = _geradorTokenService.GerarToken(usuario);

            return(token);
        }