Exemplo n.º 1
0
    public async Task <User> RequestToken(User user)
    {
        var tokenHandler    = new JwtSecurityTokenHandler();
        var key             = Encoding.ASCII.GetBytes(_jwtOptions.Secret);
        var tokenDescriptor = new SecurityTokenDescriptor
        {
            Subject = new ClaimsIdentity(new Claim[]
            {
                new Claim(ClaimTypes.Name, user.Username),
                new Claim(ClaimTypes.Role, user.Role),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                new Claim("Id", user.Id.ToString())
            }),

            Expires            = DateTime.UtcNow.AddMinutes(15),
            SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
        };
        var token = tokenHandler.CreateToken(tokenDescriptor);

        user.RefreshToken = new RefreshToken()
        {
            UserId       = user.Id,
            JwtId        = token.Id,
            CreationDate = DateTime.UtcNow,
            ExpiryDate   = DateTime.UtcNow.AddMonths(1)
        };
        user.JwtToken = tokenHandler.WriteToken(token);

        _refreshTokenRepository.Add(user.RefreshToken);
        await _userRepository.SaveChangesAsync();

        await _refreshTokenRepository.SaveChangesAsync();

        return(user);
    }
Exemplo n.º 2
0
        private async Task <(SignInResult signInResult, LoginSuccessResponse login)> AuthenticateUser(User user, LoginRequest login)
        {
            var signInResult = await _signInManager.PasswordSignInAsync(user, login.Password, false, true);

            if (!signInResult.Succeeded)
            {
                return(signInResult, null);
            }
            var principal = await _signInManager.CreateUserPrincipalAsync(user);

            var jwt          = _tokenFactory.GenerateJwtToken(principal);
            var refreshToken = new RefreshToken
            {
                Id        = _uuidService.GenerateUuId(),
                User      = user.Id,
                Value     = _tokenFactory.GenerateToken(32),
                Location  = login.Location,
                Useragent = login.UserAgent,
                IpAddress = login.IpAddress
            };

            _refreshTokenRepository.Add(refreshToken);
            var res = new LoginSuccessResponse
            {
                RefreshToken = refreshToken.Value,
                Jwt          = jwt
            };

            return(signInResult, res);
        }
Exemplo n.º 3
0
        public async Task <Unit> Handle(CreateRefreshTokenCommand request, CancellationToken cancellationToken)
        {
            var tokenRefresh = _mapper.Map <RefreshToken>(request);

            await _refreshTokenRepository.Add(tokenRefresh);

            return(new Unit());
        }
Exemplo n.º 4
0
    public async Task <string> CreateAsync(int userId)
    {
        var token = _rng.Generate(removeSpecialChars: true);
        await _refreshTokenRepository.Add(new RefreshToken(token, DateTime.UtcNow, userId, DateTime.UtcNow.AddDays(7)));


        return(token);
    }
        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
            }));
        }
Exemplo n.º 6
0
            public async Task <WebToken> Handle(GenerateWebToken request, CancellationToken cancellationToken)
            {
                if (request.User == null)
                {
                    throw new InvalidCredentialException("");
                }

                DateTime authTime       = DateTime.UtcNow;
                DateTime expirationDate = authTime.AddSeconds(_jwtOptions.ExpiresIn);

                List <Claim> claims = new List <Claim>();

                claims.Add(new Claim(JwtClaimNames.UserId, request.User.Id.ToString()));
                claims.Add(new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString("D")));
                claims.Add(new Claim(JwtRegisteredClaimNames.Email, request.User.Email));
                claims.Add(new Claim(JwtRegisteredClaimNames.AuthTime, authTime.ToString("u")));
                claims.Add(new Claim("Name", $"{request.User.FirstName} {request.User.LastName}"));

                claims.AddRange(request.Claims);

                ClaimsIdentity identity = new ClaimsIdentity(new GenericIdentity(request.User.Id.ToString()), claims);

                SecurityTokenDescriptor tokenDescriptor = new SecurityTokenDescriptor
                {
                    Audience           = _jwtOptions.Audience,
                    Issuer             = _jwtOptions.Issuer,
                    Expires            = expirationDate,
                    NotBefore          = authTime,
                    Subject            = identity,
                    SigningCredentials = _jwtSigningOptions.SigningCredentials,
                    IssuedAt           = authTime,
                };

                RefreshToken refreshToken = new RefreshToken
                {
                    UserId         = request.User.Id,
                    Token          = Guid.NewGuid(),
                    ExpirationDate = authTime.AddSeconds(_jwtOptions.RefreshTokenExpiresIn),
                    IsActive       = true,
                };

                await _refreshTokenRepository.Add(refreshToken, cancellationToken);

                SecurityToken securityToken = _jwtSecurityTokenHandler.CreateToken(tokenDescriptor);

                return(new WebToken
                {
                    Token = _jwtSecurityTokenHandler.WriteToken(securityToken),
                    ExpirationDate = expirationDate,
                    RefreshToken = refreshToken,
                    CreatedAt = DateTime.UtcNow,
                });
            }
Exemplo n.º 7
0
        public async Task <bool> AddRefreshToken(RefreshToken token)
        {
            var existingTokens = await _refreshTokenRepository.GetBySubjectAndClientId(token.Subject, token.Client.ClientId);

            if (existingTokens != null && existingTokens.Count > 0)
            {
                existingTokens.Clear();
            }
            _refreshTokenRepository.Add(token);
            await _unitOfWorkRepository.SaveChangesAsync();

            return(true);
        }
Exemplo n.º 8
0
        public async Task <bool> AddRefreshToken(RefreshToken token)
        {
            var existingToken = _refreshTokenRepository.Query(r => r.Subject == token.Subject && r.ClientId == token.ClientId).SingleOrDefault();

            if (existingToken != null)
            {
                var result = await RemoveRefreshToken(existingToken);
            }

            _refreshTokenRepository.Add(token);

            return(await _unitOfWork.SaveChangesAsync() > 0);
        }
Exemplo n.º 9
0
        public async Task <IActionResult> AuthenticateAsync(string login, string password)
        {
            var user = await userRepository.GetAsync(login);

            if (user == null || !BCrypt.Net.BCrypt.Verify(password, user.PasswordHash))
            {
                return(new JsonResult(new ExceptionDto {
                    Message = "Invalid credentials"
                })
                {
                    StatusCode = 422
                });
            }

            var tokens = jwtManager.GenerateTokens(login, await GetRoleAsync(login), DateTime.Now);

            var handler     = new JwtSecurityTokenHandler();
            var refreshData = handler.ReadJwtToken(tokens.RefreshToken);
            var date        = refreshData.ValidTo;

            await refreshTokenRepository.Add(new RefreshToken { Token = tokens.RefreshToken, ValidTill = date });

            return(new JsonResult(tokens));
        }
Exemplo n.º 10
0
        public RefreshToken GenerateRefreshToken(int applicationId, string redirectUri, Guid userId, string scope = null)
        {
            var refreshToken = new RefreshToken
            {
                RefreshTokenId = _passwordGenerator.Generate(_settings.RefreshTokenLength),
                ApplicationId  = applicationId,
                ExpirationDate = DateTime.UtcNow.AddDays(_settings.RefreshTokenLifetimeDays),
                RedirectUri    = redirectUri,
                UserId         = userId,
                Scope          = scope
            };

            _refreshTokenRepository.Add(refreshToken);

            return(refreshToken);
        }
Exemplo n.º 11
0
 public void Save(RefreshToken token)
 {
     using (var transaction = Connection.BeginTransaction())
     {
         try
         {
             refreshTokenRepository.Add(token);
             transaction.Commit();
         }
         catch
         {
             transaction.Rollback();
             throw;
         }
     }
 }
Exemplo n.º 12
0
        public bool AddRefreshToken(RefreshToken token)
        {
            var tokens        = _authService.GetAllRefreshTokens();
            var existingToken = tokens.FirstOrDefault(p => p.Subject == token.Subject && p.ClientId == token.ClientId);

            if (existingToken != null)
            {
                RemoveRefreshToken(token);
            }

            token.Subject = "s";
            _refreshTokenRepository.Add(token);
            // _authService.AddRefreshToken(token);

            return(true);
        }
Exemplo n.º 13
0
        private async Task <RefreshToken> CreateInternalAsync(User user)
        {
            var tokenId     = Guid.NewGuid();
            var userClaims  = user.ExtractUserClaims();
            var jwtToken    = CreateJwtToken(userClaims, tokenId);
            var jwtTokenStr = _jwtSecurityTokenHandler.WriteToken(jwtToken);

            var refreshToken = new RefreshToken(user.Id, jwtTokenStr);

            refreshToken = refreshToken.Bind(x => x.Id, tokenId);

            _refreshTokenRepository.Add(refreshToken);
            await _refreshTokenRepository.UnitOfWork.SaveChangesAndDispatchDomainEventsAsync();

            return(refreshToken);
        }
        public async Task <RefreshTokenDto> GetNew(string userId, string accessToken)
        {
            await _refreshTokenRepository.RemoveByUserIdAsync(userId);

            var refreshToken = new RefreshToken()
            {
                UserId = userId, AccessToken = accessToken
            };

            _refreshTokenRepository.Add(refreshToken);
            await _unitOfWork.CompleteAsync();

            var refreshTokenDto = _mapper.Map <RefreshToken, RefreshTokenDto>(refreshToken);

            return(refreshTokenDto);
        }
        public async Task Handle(TokenCreatedEvent notification, CancellationToken cancellationToken)
        {
            // The old token is removed, if it exists
            if (!string.IsNullOrEmpty(notification.OldToken))
            {
                await _refreshTokenRepository.Remove(notification.UserId, notification.OldToken);
            }

            // The refresh token is added to the database
            if (notification.NewToken != null)
            {
                var refreshToken = new RefreshToken(notification.UserId,
                                                    notification.NewToken.RefreshToken,
                                                    notification.NewToken.RefreshTokenExpiration);
                await _refreshTokenRepository.Add(refreshToken);
            }
        }
Exemplo n.º 16
0
        private string CreateRefreshToken(string JwtTokenId, string userId)
        {
            var refreshToken = new RefreshToken()
            {
                Token       = Guid.NewGuid().ToString(),
                JwtId       = JwtTokenId,
                UserId      = userId,
                CreateTime  = DateTime.Now,
                ExpiryDate  = DateTime.Now.AddMonths(2),
                Used        = false,
                Invalidated = false
            };

            _refreshTokenRepository.Add(refreshToken);
            if (_refreshTokenRepository.SaveChanges() == 1)
            {
                return(refreshToken.Token);
            }
            return(null);
        }
Exemplo n.º 17
0
        public async Task <string> GenerateRefreshToken(T user)
        {
            Guid         refreshTokenGuid = Guid.NewGuid();
            RefreshToken newToken         = new RefreshToken
            {
                UserId = user.Id,
                Token  = refreshTokenGuid,
                Expiry = DateTime.Now.AddYears(1)
            };

            RefreshToken existingToken = this.refreshTokenRepository.GetAll().Where(x => x.UserId == user.Id).FirstOrDefault();

            if (existingToken != null)
            {
                await refreshTokenRepository.Delete(existingToken);
            }
            await refreshTokenRepository.Add(newToken);

            return(refreshTokenGuid.ToString());
        }
Exemplo n.º 18
0
        public async Task CreateAsync(AuthenticationTokenCreateContext context)
        {
            var clientId = context.Ticket.Properties.Dictionary[GenericNames.AUTHENTICATION_CLIENT_ID_KEY];

            if (string.IsNullOrEmpty(clientId))
            {
                return;
            }

            var refreshTokenLifeTime = context.OwinContext.Get <int>(GenericNames.OWIN_CONTEXT_REFRESH_TOKEN_LIFETIME);

            var refreshToken = Guid.NewGuid().ToString("n");

            //var refreshTokenRepository = new RefreshTokenRepository(context.OwinContext.Get<ManahostManagerDAL>());
            /*var ClientManager = ClientUserManager.Create(null, context.OwinContext.Get<ManahostManagerDAL>());*/

            IDependencyScope        Scope                  = context.OwinContext.Get <IDependencyScope>();
            ClientUserManager       ClientManager          = Scope.GetService(typeof(ClientUserManager)) as ClientUserManager;
            IRefreshTokenRepository refreshTokenRepository = Scope.GetService(typeof(IRefreshTokenRepository)) as IRefreshTokenRepository;

            var ServiceRepository = new ServiceRepository(context.OwinContext.Get <ManahostManagerDAL>());

            var client = await ClientManager.FindByEmailAsync(context.Ticket.Identity.Name);

            var service = ServiceRepository.GetUniq(x => x.Id == clientId);

            var token = new RefreshToken()
            {
                Id         = refreshToken,
                Client     = client,
                Service    = service,
                IssuedUtc  = DateTime.UtcNow,
                ExpiresUtc = DateTime.UtcNow.AddMinutes(Convert.ToDouble(refreshTokenLifeTime))
            };

            token.ProtectedTicket = context.SerializeTicket();
            refreshTokenRepository.Add(token);
            await refreshTokenRepository.SaveAsync();

            context.SetToken(refreshToken);
        }
Exemplo n.º 19
0
        public bool Add(RefreshToken refreshToken)
        {
            var existingRefreshToken = _refreshTokenRepository
                                       .GetSingleByCondition(x => x.ClientId == refreshToken.ClientId &&
                                                             x.UserName == refreshToken.UserName);

            if (existingRefreshToken != null)
            {
                var resultRemove = _refreshTokenRepository.Delete(existingRefreshToken);
                if (resultRemove == null)
                {
                    return(false);
                }
            }
            var entity = _refreshTokenRepository.Add(refreshToken);

            if (entity == null)
            {
                return(false);
            }
            _unitOfWork.Commit();
            return(true);
        }
        private void SaveRefreshToken(int userId, string refreshToken, DateTime tokenExpiration)
        {
            //saves the refresh token to a data store
            var oldRefreshToken = _refreshTokenRepository.Get().SingleOrDefault(x => x.UserId == userId);

            if (oldRefreshToken != null)
            {
                oldRefreshToken.Value           = refreshToken;
                oldRefreshToken.TokenExpiration = tokenExpiration;
                _refreshTokenRepository.Update(oldRefreshToken);
            }
            else
            {
                var entity = new RefreshToken
                {
                    Value           = refreshToken,
                    UserId          = userId,
                    TokenExpiration = tokenExpiration
                };
                _refreshTokenRepository.Add(entity);
            }

            _unitOfWork.Commit();
        }
Exemplo n.º 21
0
        private RefreshTokenData GenerateRefreshToken(string userId)
        {
            string token;
            var    randomNumber = new byte[32];

            using (var rng = RandomNumberGenerator.Create())
            {
                rng.GetBytes(randomNumber);
                token = Convert.ToBase64String(randomNumber);
            }

            var refreshToken = new RefreshTokenData
            {
                UsuarioId      = userId,
                ExpirationDate = DateTime.Now.AddMinutes(_tokenDescriptor.MinutesRefreshTokenValid),
                RefreshToken   = token.Replace("+", string.Empty)
                                 .Replace("=", string.Empty)
                                 .Replace("/", string.Empty)
            };

            _refreshTokenRepository.Add(refreshToken);

            return(refreshToken);
        }
Exemplo n.º 22
0
 public async Task <bool> AddRefreshTokenAsync(RefreshToken refreshToken)
 {
     _repository.Add(refreshToken);
     return(await _repository.UnitOfWork.SaveChangesAsync() > 0);
 }
Exemplo n.º 23
0
 public void AddRefreshToken(RefreshToken token)
 {
     _refreshTokenRepository.Add(token);
     _unitOfWork.Commit();
 }
Exemplo n.º 24
0
 public bool AddRefreshToken(RefreshToken token)
 {
     _refreshTokenRepository.Add(token);
     return(true);
 }