public AuthenticationResponse Authenticate(string username, Claim[] claims)
        {
            var key = Encoding.ASCII.GetBytes(tokenKey);
            var jwtSecurityToken = new JwtSecurityToken(
                claims: claims,
                expires: DateTime.UtcNow.AddHours(1),
                signingCredentials: new SigningCredentials(
                    new SymmetricSecurityKey(key),
                    SecurityAlgorithms.HmacSha256Signature)
                );

            var token        = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);
            var refreshToken = refreshTokenGenerator.GenerateToken();

            if (UsersRefreshTokens.ContainsKey(username))
            {
                UsersRefreshTokens[username] = refreshToken;
            }
            else
            {
                UsersRefreshTokens.Add(username, refreshToken);
            }

            return(new AuthenticationResponse
            {
                JwtToken = token,
                RefreshToken = refreshToken
            });
        }
        public AuthenticationResponse Authenticate(string username, string password)
        {
            if (!users.Any(u => u.Key == username && u.Value == password))
            {
                return(null);
            }
            var tokenHandler    = new JwtSecurityTokenHandler();
            var tokenKey        = Encoding.ASCII.GetBytes(key);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.Name, username)
                }),
                Expires            = DateTime.UtcNow.AddHours(1),
                SigningCredentials = new SigningCredentials(
                    new SymmetricSecurityKey(tokenKey), SecurityAlgorithms.HmacSha256Signature
                    )
            };
            var token        = tokenHandler.CreateToken(tokenDescriptor);
            var refreshToken = refreshTokenGenerator.GenerateToken();

            if (UsersRefreshTokens.ContainsKey(username))
            {
                UsersRefreshTokens[username] = refreshToken;
            }
            else
            {
                UsersRefreshTokens.Add(username, refreshToken);
            }
            return(new AuthenticationResponse {
                JwtToken = tokenHandler.WriteToken(token), RefreshToken = refreshToken
            });
        }
        public async Task <AuthenticationResponse> Authenticate(string username, string password)
        {
            var userAuthResult =
                await ApiClient.UserAuth(_userApiUri, new UserCred { Username = username, Password = password });

            if (userAuthResult?.Code != 0)
            {
                return(null);
            }

            var tokenCreatedAt = DateTime.Now;
            var token          = GenerateTokenString(username, tokenCreatedAt);
            var refreshToken   = _refreshTokenGenerator.GenerateToken();

            using (var scope = _serviceProvider.CreateScope()) {
                var dbRepository = scope.ServiceProvider.GetRequiredService <IDbRepository>();

                var entity = await dbRepository.Get <DbUserToken>()
                             .FirstOrDefaultAsync(x => x.UserId == userAuthResult.User.Id);

                if (entity == null)
                {
                    entity = new DbUserToken(Guid.NewGuid())
                    {
                        Username       = userAuthResult.User.Username,
                        Token          = token,
                        RefreshToken   = refreshToken,
                        TokenCreatedAt = tokenCreatedAt,
                        Expires        = tokenCreatedAt.AddMinutes(2),
                        UserId         = userAuthResult.User.Id
                    };
                    await dbRepository.Add(entity);
                }
                else
                {
                    entity.Token          = token;
                    entity.RefreshToken   = refreshToken;
                    entity.TokenCreatedAt = tokenCreatedAt;
                    entity.Expires        = tokenCreatedAt.AddMinutes(2);
                    await dbRepository.Update(entity);
                }

                await dbRepository.SaveChangesAsync();
            }

            return(new AuthenticationResponse {
                Token = token,
                RefreshToken = refreshToken,
                Expires = tokenCreatedAt.AddMinutes(2),
                Code = (int)ActionResult.Success,
                Message = ActionResult.Success.ToDescription()
            });
        }
        public TokenResponse Authenticate(string username, string password)
        {
            try
            {
                DateTime tokenCreatedDate = DateTime.UtcNow;

                var token        = GenerateTokenString(username, tokenCreatedDate);
                var refreshToken = refreshTokenGenerator.GenerateToken();

                if (token == null || refreshToken == null)
                {
                    return(new TokenResponse
                    {
                        IsSuccess = false,
                        Message = "Failure: Unable to generate token.",
                    });
                }

                if (UsersRefreshTokens.ContainsKey(username))
                {
                    UsersRefreshTokens[username] = refreshToken;
                }
                else
                {
                    UsersRefreshTokens.Add(username, refreshToken);
                }

                return(new TokenResponse
                {
                    JwtToken = token,
                    RefreshToken = refreshToken,
                    CreatedDate = tokenCreatedDate,
                    ExpiryDate = tokenCreatedDate.AddMinutes(2),
                    IsSuccess = true,
                    Message = "Success: Token generated.",
                });
            }
            catch (Exception exception)
            {
                return(new TokenResponse
                {
                    IsSuccess = false,
                    Message = $"Server Failure: {exception.Message}",
                });
            }
        }
Ejemplo n.º 5
0
        /// <summary>
        /// This method is used to authenticate user.
        /// </summary>
        /// <param name="userDTO">User who is authenticating.</param>
        /// <returns>JSON Web Token.</returns>
        public async Task <AuthenticationResponse> Login(UserDTO userDTO)
        {
            var user = await Database.UserManager.FindByNameAsync(userDTO.Username);

            if (user != null && await Database.UserManager.CheckPasswordAsync(user, userDTO.Password))
            {
                if (!await Database.UserManager.IsEmailConfirmedAsync(user))
                {
                    throw new ValidationException("Email is not confirmed");
                }
                var role = await Database.UserManager.GetRolesAsync(user);

                IdentityOptions _options        = new IdentityOptions();
                var             tokenDescriptor = new SecurityTokenDescriptor
                {
                    Subject = new ClaimsIdentity(new Claim[]
                    {
                        new Claim("UserID", user.Id.ToString()),
                        new Claim(_options.ClaimsIdentity.RoleClaimType, role.FirstOrDefault())
                    }),
                    Expires            = DateTime.UtcNow.AddHours(1),
                    SigningCredentials = new SigningCredentials(new SymmetricSecurityKey
                                                                    (Encoding.UTF8.GetBytes(_appSettings.JWT_Secret)),
                                                                SecurityAlgorithms.HmacSha256Signature)
                };
                var tokenHandler  = new JwtSecurityTokenHandler();
                var securityToken = tokenHandler.CreateToken(tokenDescriptor);
                var token         = tokenHandler.WriteToken(securityToken);
                var refreshToken  = _refreshTokenGenerator.GenerateToken();

                user.RefreshToken = refreshToken;
                Database.Users.Update(user);
                await Database.SaveAsync();

                return(new AuthenticationResponse()
                {
                    JwtToken = token, RefreshToken = refreshToken
                });
            }
            else
            {
                throw new ValidationException("Username or password is incorrect");
            }
        }
        public AuthenticationResponse Authenticate(string username, Claim[] claims)
        {
            var token        = GenerateTokenString(username, DateTime.UtcNow, claims);
            var refreshToken = refreshTokenGenerator.GenerateToken();

            if (UsersRefreshTokens.ContainsKey(username))
            {
                UsersRefreshTokens[username] = refreshToken;
            }
            else
            {
                UsersRefreshTokens.Add(username, refreshToken);
            }

            return(new AuthenticationResponse
            {
                JwtToken = token,
                RefreshToken = refreshToken
            });
        }
Ejemplo n.º 7
0
        public AuthenticationResponse Authenticate(string username, Claim[] claims, string refreshToken)
        {
            var tokenKey         = Encoding.ASCII.GetBytes(key);
            var jwtSecurityToken = new JwtSecurityToken(
                claims: claims,
                expires: DateTime.UtcNow.AddHours(1),
                signingCredentials: new SigningCredentials(
                    new SymmetricSecurityKey(tokenKey),
                    SecurityAlgorithms.HmacSha256Signature
                    )
                );
            var token       = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);
            var accessToken = refreshTokenGenerator.GenerateToken();

            return(new AuthenticationResponse {
                AccessToken = accessToken, RefreshToken = refreshToken
            });
        }