Exemplo n.º 1
0
        public async Task <ActionResult <User> > Login(User user)
        {
            var currentUser = await _userManager.FindByEmailAsync(user.Email);

            if (currentUser == null)
            {
                return(StatusCode(StatusCodes.Status401Unauthorized));
            }

            var result = await _signInManager.CheckPasswordSignInAsync(currentUser, user.Password, false);

            if (result.Succeeded)
            {
                var refreshToken = RefreshTokenGenerator.GenerateRefreshToken();

                currentUser.RefreshToken = refreshToken;
                _context.Update(currentUser);
                _context.SaveChanges();

                Response.Cookies.Append("refresh-token", refreshToken, new CookieOptions
                {
                    HttpOnly    = true,
                    IsEssential = true
                });

                return(new User
                {
                    DisplayName = currentUser.UserName,
                    Token = _jwtGenerator.GenerateToken(currentUser),
                    Username = currentUser.UserName
                });
            }

            return(StatusCode(StatusCodes.Status401Unauthorized));
        }
 public Authenticator(AccessTokenGenerator accessTokenGenerator, RefreshTokenGenerator refreshTokenGenerator,
                      IRefreshTokenRepository refreshTokenRepository)
 {
     _accessTokenGenerator   = accessTokenGenerator;
     _refreshTokenGenerator  = refreshTokenGenerator;
     _refreshTokenRepository = refreshTokenRepository;
 }
Exemplo n.º 3
0
        public RegisterResponse Register(RegisterRequest request)
        {
            var userExists = _context.Client.Any(c => c.Login.Equals(request.Login));

            if (userExists)
            {
                throw new UserAlreadyExistsException("User already Exists!");
            }

            var salt = SaltGenerator.CreateSalt();

            var newClient = new Client()
            {
                FirstName           = request.FirstName,
                LastName            = request.LastName,
                Email               = request.Email,
                Phone               = request.Phone,
                Login               = request.Login,
                Password            = HashGenerator.CreateHashForPassword(request.Password, salt),
                Salt                = salt,
                RefreshToken        = RefreshTokenGenerator.CreateRefreshToken(),
                TokenExpirationDate = DateTime.Now.AddDays(7)
            };

            var newClientClaims = new[]
            {
                new Claim(ClaimTypes.NameIdentifier, Convert.ToString(newClient.IdClient)),
                new Claim(ClaimTypes.Name, newClient.Login),
                new Claim(ClaimTypes.Role, "Client")
            };

            var key         = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["SecretKey"]));
            var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var token = new JwtSecurityToken(
                issuer: "*****@*****.**",
                audience: "Clients",
                claims: newClientClaims,
                expires: DateTime.Now.AddMinutes(10),
                signingCredentials: credentials
                );


            _context.Client.Add(newClient);
            _context.SaveChanges();

            return(new RegisterResponse()
            {
                FirstName = newClient.FirstName,
                LastName = newClient.LastName,
                Email = newClient.Email,
                Phone = newClient.Phone,
                Login = newClient.Login,
                AccessToken = new JwtSecurityTokenHandler().WriteToken(token),
                RefreshToken = newClient.RefreshToken
            });
        }
        public SignInServiceTest()
        {
            var context = new MaktoobDbContext(new DbContextOptionsBuilder <MaktoobDbContext>().UseInMemoryDatabase("MaktoobDb").Options);

            _errorDescriber = new GErrorDescriber();
            var keyNormalizer       = new NameNormalizer();
            var passwordHasher      = new PasswordHasher();
            var unitOfWork          = new UnitOfWork(context);
            var userRepository      = new UserRepository(context, unitOfWork);
            var userLoginRepository = new UserLoginRepository(context, unitOfWork);
            var userValidator       = new IValidator <User>[] { new UserValidator(userRepository, keyNormalizer, _errorDescriber) };

            _userService = new UserService(userRepository, _errorDescriber, keyNormalizer, passwordHasher, userValidator);
            var jsonWebTokenOptions = new JsonWebTokenOptions
            {
                Issuer       = "issuer",
                Audience     = "audience",
                Algorithm    = "HS256",
                Key          = "super secret key",
                Expires      = TimeSpan.Parse("00:00:01"), // 1 seconds
                RefreshToken = new RefreshTokenOptions
                {
                    Expires        = TimeSpan.Parse("00:00:10"), // 10 seconds
                    UpdateRequired = TimeSpan.Parse("00:00:05")  // 5 seconds
                }
            };
            var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jsonWebTokenOptions.Key));
            JwtBearerOptions jwtBearerOptions = new JwtBearerOptions
            {
                TokenValidationParameters = new TokenValidationParameters
                {
                    IssuerSigningKey         = securityKey,
                    ValidIssuer              = jsonWebTokenOptions.Issuer,
                    ValidAudience            = jsonWebTokenOptions.Audience,
                    ValidateAudience         = !string.IsNullOrWhiteSpace(jsonWebTokenOptions.Audience),
                    ValidateIssuer           = !string.IsNullOrWhiteSpace(jsonWebTokenOptions.Issuer),
                    ValidateIssuerSigningKey = true,
                    ClockSkew        = TimeSpan.Zero,
                    ValidateLifetime = true
                }
            };
            var jsonWebTokenCoder     = new JsonWebTokenCoder(Options.Create(jsonWebTokenOptions));
            var userClaimsFactory     = new UserClaimsFactory();
            var refreshTokenGenerator = new RefreshTokenGenerator();

            _signInService = new SignInService(_userService,
                                               jsonWebTokenCoder, userLoginRepository,
                                               _errorDescriber, userClaimsFactory, refreshTokenGenerator, null,
                                               Options.Create(jsonWebTokenOptions));
        }
Exemplo n.º 5
0
        public LoginResponse RefreshJwtToken(string refreshToken)
        {
            var client = _context.Client.SingleOrDefault(p => p.RefreshToken == refreshToken);

            if (client == null)
            {
                throw new UserDoesntExistExcetion("Couldn't find user with this refresh token");
            }
            if (client.TokenExpirationDate < DateTime.Now)
            {
                throw new RefreshTokenExpiredException("Refresh token has expired");
            }

            var clientClaims = new[]
            {
                new Claim(ClaimTypes.NameIdentifier, Convert.ToString(client.IdClient)),
                new Claim(ClaimTypes.Name, client.Login),
                new Claim(ClaimTypes.Role, "Client")
            };

            var key         = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["SecretKey"]));
            var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var token = new JwtSecurityToken(
                issuer: "*****@*****.**",
                audience: "Clients",
                claims: clientClaims,
                expires: DateTime.Now.AddMinutes(10),
                signingCredentials: credentials
                );

            client.RefreshToken        = RefreshTokenGenerator.CreateRefreshToken();
            client.TokenExpirationDate = DateTime.Now.AddDays(7);
            _context.SaveChanges();

            return(new LoginResponse()
            {
                AccessToken = new JwtSecurityTokenHandler().WriteToken(token),
                RefreshToken = client.RefreshToken
            });
        }
Exemplo n.º 6
0
        public LoginResponse Login(LoginRequest request)
        {
            var client = _context.Client.SingleOrDefault(p => p.Login == request.Login);

            if (client == null)
            {
                throw new UserDoesntExistExcetion($"User with {request.Login} login doesn't exist");
            }
            if (!client.Password.Equals(HashGenerator.CreateHashForPassword(request.Password, client.Salt)))
            {
                throw new WrongPasswordException("Wrong Password!");
            }
            var clientClaims = new[]
            {
                new Claim(ClaimTypes.NameIdentifier, Convert.ToString(client.IdClient)),
                new Claim(ClaimTypes.Name, client.Login),
                new Claim(ClaimTypes.Role, "Client")
            };
            var key         = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["SecretKey"]));
            var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var token = new JwtSecurityToken(
                issuer: "*****@*****.**",
                audience: "Clients",
                claims: clientClaims,
                expires: DateTime.Now.AddMinutes(10),
                signingCredentials: credentials
                );

            client.RefreshToken        = RefreshTokenGenerator.CreateRefreshToken();
            client.TokenExpirationDate = DateTime.Now.AddDays(7);
            _context.SaveChanges();

            return(new LoginResponse()
            {
                AccessToken = new JwtSecurityTokenHandler().WriteToken(token),
                RefreshToken = client.RefreshToken
            });
        }
Exemplo n.º 7
0
 public AuthenticationController(IUserRepository userRepository, IPasswordHasher passwordHasher, AccessTokenGenerator accessTokenGenerator, RefreshTokenGenerator refreshTokenGenerator, RefreshTokenValidator refreshTokenValidator, IRefreshTokenRepository refreshTokenRepository, Authenticator authenticator)
 {
     _userRepository         = userRepository;
     _passwordHasher         = passwordHasher;
     _refreshTokenValidator  = refreshTokenValidator;
     _refreshTokenRepository = refreshTokenRepository;
     _authenticator          = authenticator;
 }