private async Task <OkObjectResult> GenerateToken(int userId, string name, string email)
        {
            // https://github.com/wellingtonjhn/DemoJwt/blob/master/src/DemoJwt.Application/Services/JwtService.cs
            // https://openid.net/specs/openid-connect-core-1_0.html#ClaimsContents

            var claims = new[]
            {
                new Claim(JwtRegisteredClaimNames.NameId, userId.ToString()),
                new Claim(JwtRegisteredClaimNames.GivenName, name),
                new Claim(JwtRegisteredClaimNames.Email, email),

                //new Claim(ClaimTypes.Role, "Admin")
                // p/ policy:
                // new Claim("permissions", policy)
            };


            //recebe uma instancia da classe SymmetricSecurityKey
            //armazenando a chave de criptografia usada na criação do token
            var key = new SymmetricSecurityKey(
                Encoding.UTF8.GetBytes(_configuration["SecurityKey"]));

            //recebe um objeto do tipo SigninCredentials contendo a chave de
            //criptografia e o algoritmo de segurança empregados na geração
            // de assinaturas digitais para tokens
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var token = new JwtSecurityToken(
                issuer: "fansoft.com.br",
                audience: "fansoft.com.br",
                claims: claims,
                expires: DateTime.UtcNow.AddMinutes(5),
                notBefore: DateTime.UtcNow,
                signingCredentials: creds);

            var refreshTokenOld = await _refreshTokenRepository.GetByUserIdAsync(userId);

            if (refreshTokenOld != null)
            {
                _refreshTokenRepository.Del(refreshTokenOld);
            }

            var refreshTokenData = new RefreshToken(userId, Guid.NewGuid().ToString("N").ToUpper());

            _refreshTokenRepository.Add(refreshTokenData);

            await _uow.CommitAsync();


            return(Ok(new
            {
                token = new JwtSecurityTokenHandler().WriteToken(token),
                refreshToken = refreshTokenData.Token
            }));
        }
Esempio n. 2
0
        public async Task <JwtDTO> Login(string login, string password)
        {
            var user = await _userRepository.GetAsync(login);

            if (user == null)
            {
                throw new NewException(NewCodes.UserNotFound);
            }
            var hash = _encrypter.GetHash(password, user.Salt);

            if (user.Password != hash)
            {
                throw new NewException(NewCodes.WrongCredentials);
            }
            var jwt          = _jwtHandler.CreateToken(user.Id);
            var refreshToken = await _refreshTokens.GetByUserIdAsync(user.Id);

            string token = "";

            if (refreshToken == null)
            {
                token = Guid.NewGuid().ToString()
                        .Replace("+", string.Empty)
                        .Replace("=", string.Empty)
                        .Replace("/", string.Empty);
                await _refreshTokens.AddAsync(new RefreshToken(user, token));
            }
            else
            {
                token = refreshToken.Token;
            }
            var jwtDto = new JwtDTO()
            {
                AccessToken = jwt.AccessToken, Expires = jwt.Expires, RefreshToken = token, UserId = jwt.UserId
            };

            return(jwtDto);
        }