Пример #1
0
        public ActionResult Token(string username, string password)
        {
            //sleep timer to demonstrate the loading bar
            Thread.Sleep(2000);
            //get user from data store
            var user = userService.GetByName(username);

            //validate password
            if (user == null)
            {
                return(BadRequest("Invalid credentials"));
            }
            if (user.Active != true)
            {
                return(BadRequest("Account not active"));
            }
            if (hashingService.VerifyHashedPassword(user.PasswordHash, password) == PasswordVerificationResult.Failed)
            {
                return(BadRequest("Invalid credentials"));
            }
            //create claims
            var claims = new List <Claim> {
                new Claim("uid", user.Id.ToString(CultureInfo.InvariantCulture), ClaimValueTypes.Integer)
            };
            //create tokens
            var accessToken  = jwtTokenService.GenerateAccessToken(user.UserName, null, claims);
            var refreshToken = jwtTokenService.GenerateRefreshToken();

            //store refresh token
            jwtTokenService.StoreRefreshToken(user.Id, refreshToken);
            return(Ok(new JwtToken {
                AccessToken = accessToken, RefreshToken = refreshToken, TokenType = "bearer"
            }));
        }
Пример #2
0
        public async Task <Results <RefreshTokenContract> > Login(PandaUserLoginContract account)
        {
            var refreshTokenIsNullOrEmpty = await _userLogic.RefreshTokenIsNullOrEmpty(account.Email);

            if (!refreshTokenIsNullOrEmpty)
            {
                return(PandaResponse.CreateErrorResponse <RefreshTokenContract>("User still loged in."));
            }

            var signInResult = await _userLogic.Login(account);

            if (signInResult.IsError())
            {
                return(PandaResponse.CreateErrorResponse <RefreshTokenContract>(signInResult.Errors.ToArray()));
            }
            account.Id = signInResult.Data.Id;

            var token        = _jwtTokenService.GenerateToken(account.Email, account.Id.ToString());
            var refreshToken = _jwtTokenService.GenerateRefreshToken();
            var tokenData    = new RefreshTokenContract {
                RefreshToken = refreshToken, Token = token
            };

            var refreshTokenResult = await _userLogic.UpdateRefreshTokenToUser(account.Email, refreshToken);

            if (refreshTokenResult.IsError())
            {
                return(PandaResponse.CreateErrorResponse <RefreshTokenContract>(refreshTokenResult.Errors.ToArray()));
            }
            return(PandaResponse.CreateSuccessResponse(tokenData));
        }
Пример #3
0
        public async Task <ActionResult <TokenResult> > Refresh([FromForm] string token, [FromForm] string refreshToken)
        {
            ClaimsPrincipal principal = _tokenService.GetPrincipalFromExpiredToken(token);
            string          name      = GetNameFromClaimsPrincipal(principal);
            string          email     = GetEmailFromClaimsPrincipal(principal);

            User user = await _userManager.FindByEmailAsync(email);

            string savedRefreshToken = user.RefreshToken;

            if (savedRefreshToken != refreshToken)
            {
                throw new SecurityTokenException("Invalid refresh token");
            }

            string newJwtToken     = _tokenService.BuildToken(name, email);
            string newRefreshToken = _tokenService.GenerateRefreshToken();

            user.RefreshToken = newRefreshToken;
            await _userManager.UpdateAsync(user);

            return(Ok(new TokenResult
            {
                Token = newJwtToken,
                RefreshToken = newRefreshToken
            }));
        }
Пример #4
0
        public async Task <IActionResult> Login(UserForLoginDto loginDto)
        {
            var userFromRepo = await _repo.Login(loginDto.Username, loginDto.Password);

            if (userFromRepo == null)
            {
                return(Unauthorized());
            }

            return(Ok(new
            {
                token = _tokenService.GenerateAccessToken(userFromRepo, DateTime.UtcNow.AddDays(1)),
                refreshToken = _tokenService.GenerateRefreshToken(userFromRepo, DateTime.UtcNow.AddDays(30))
            }));
        }
        public async Task <ActionResult <TokenResponseDTO> > GetToken(LoginDTO credentials)
        {
            if (credentials == null)
            {
                return(BadRequest("No credentials were found"));
            }

            var user = await _userManager.FindByEmailAsync(credentials.Username);

            var refreshToken = await _tokenService.GenerateRefreshToken(user.Id);

            HttpContext.Response.Cookies.Append("MyKey", refreshToken.Token, new CookieOptions
            {
                HttpOnly    = true,
                Expires     = DateTimeOffset.FromUnixTimeMilliseconds(refreshToken.Expiration),
                IsEssential = true,
                SameSite    = SameSiteMode.None,
                Secure      = true
            });

            var accessToken = new TokenResponseDTO
            {
                Token = await _tokenService.RequestToken(credentials)
            };

            return(Ok(accessToken));
        }
        public async Task <IActionResult> Login(LoginModel model)
        {
            var user = await _userManager.FindByNameAsync(model.UserName).ConfigureAwait(false);

            if (user != null)
            {
                var result = await _signInManager.CheckPasswordSignInAsync(user, model.Password, lockoutOnFailure : true).ConfigureAwait(false);

                if (result.Succeeded == false)
                {
                    throw new UnauthorizedAccessException(AccountController.InvalidDataException);
                }

                var claims = AccountController.FillClaims(user);

                var token        = _jwtTokenService.GenerateJwtToken(claims, model.IsRememberMe);
                var refreshToken = _jwtTokenService.GenerateRefreshToken();

                user.RefreshToken = refreshToken;
                await _userManager.UpdateAsync(user).ConfigureAwait(false);

                return(Ok(new {
                    token = token,
                    refreshToken = refreshToken
                }));
            }

            throw new KeyNotFoundException(AccountController.UserNotFoundException);
        }
Пример #7
0
        public async Task <IActionResult> SignIn([FromBody] GenericUserContract account)
        {
            GenericUser accountData = await _accountFacade.SignIn(account);

            var response = LinqExtensions.CreateErrorResponse <RefreshTokenContract>("Unauthorized");

            if (accountData != null)
            {
                var token        = _jwtTokenService.GenerateToken(accountData.Email, accountData.Id.ToString());
                var refreshToken = _jwtTokenService.GenerateRefreshToken();
                var tokenData    = new RefreshTokenContract {
                    RefreshToken = refreshToken, Token = token
                };
                response = LinqExtensions.CreateSuccessResponse(tokenData);
            }
            return(Ok(response));
        }
        public async Task <AuthorizeTokenResponse> GetTokenAsync(
            AuthorizeTokenRequest request,
            CancellationToken cancellationToken)
        {
            var result = new AuthorizeTokenResponse();

            if (!await _userService.IsValidUserAsync(request.UserName, request.Password, cancellationToken))
            {
                return(result);
            }

            var claims = new[]
            {
                new Claim(ClaimTypes.Name, request.UserName)
            };

            try
            {
                result.Success      = true;
                result.AccessToken  = _jwtTokenService.GenerateAccessToken(claims);
                result.ExpiresIn    = DateTimeOffset.UtcNow.AddMinutes(_jwtTokenOptions.AccessExpiration).Ticks;
                result.RefreshToken = _jwtTokenService.GenerateRefreshToken();

                await _userService.UpdateRefreshTokenAsync(
                    request.UserName,
                    result.RefreshToken,
                    DateTime.Now.Add(TimeSpan.FromMinutes(_jwtTokenOptions.AccessExpiration)),
                    cancellationToken);
            }
            catch
            {
                result.Success = false;
            }

            return(result);
        }
Пример #9
0
            public async Task <LoginResult> Handle(AuthCommand request, CancellationToken cancellationToken)
            {
                User user = await _userManager.FindByEmailAsync(request.Email);

                bool validCredentials = await _userManager.CheckPasswordAsync(user, request.Password);

                if (!validCredentials)
                {
                    throw new InvalidCredentialException("Username or password is incorrect");
                }

                string newJwtToken     = _tokenService.BuildToken($"{user.FirstName} {user.LastName}", request.Email);
                string newRefreshToken = _tokenService.GenerateRefreshToken();

                user.RefreshToken = newRefreshToken;
                await _userManager.UpdateAsync(user);

                return(new LoginResult
                {
                    Token = newJwtToken,
                    RefreshToken = newRefreshToken
                });
            }
        public async Task <IActionResult> Refresh(RefreshTokenModel requestModel)
        {
            var principal = _jwtTokenService.GetPrincipalFromExpiredToken(requestModel.Token);
            var username  = principal.Claims.SingleOrDefault(x => x.Type == TokenClaims.UserName).Value;

            var user = await _userManager.FindByNameAsync(username).ConfigureAwait(false);

            if (user == null || user.RefreshToken != requestModel.RefreshToken)
            {
                return(BadRequest());
            }

            var newJwtToken     = _jwtTokenService.GenerateJwtToken(principal.Claims, null);
            var newRefreshToken = _jwtTokenService.GenerateRefreshToken();

            user.RefreshToken = newRefreshToken;
            await _userManager.UpdateAsync(user).ConfigureAwait(false);

            return(Ok(new
            {
                token = newJwtToken,
                refreshToken = newRefreshToken
            }));
        }
Пример #11
0
 private string GenerateRefreshToken()
 {
     return(_tokenService.GenerateRefreshToken());
 }