Exemplo n.º 1
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));
        }
Exemplo n.º 2
0
        public async Task <IActionResult> RefreshToken([FromBody] RefreshTokenContract token)
        {
            if (!ModelState.IsValid)
            {
                return(StatusCode(500,
                                  new
                {
                    Error = ModelState.Values.SelectMany(s => s.Errors.Select(ss => ss.ErrorMessage)).ToList(),
                    Structure = new RefreshTokenContract {
                    }
                }
                                  ));
            }

            var result = await _gatewayFacade.GateWayInvoke(
                method : BaseMethod,
                token : Token,
                path : BasePath,
                token,
                query : BaseQueryString
                );

            if (result.IsError())
            {
                return(StatusCode(500, result));
            }
            return(Ok(result));
        }
Exemplo n.º 3
0
        public async Task <Results <RefreshTokenContract> > RefreshToken(RefreshTokenContract token)
        {
            var principal = _jwtTokenService.GetPrincipalFromExpiredToken(token.Token);

            if (principal == null)
            {
                return(PandaResponse.CreateErrorResponse <RefreshTokenContract>("Invalid refresh token"));
            }

            var email = _jwtTokenService.GetValueFromClaimType(principal, JwtRegisteredClaimNames.Email);

            if (string.IsNullOrEmpty(email))
            {
                return(PandaResponse.CreateErrorResponse <RefreshTokenContract>("Invalid claim email"));
            }

            var userId = _jwtTokenService.GetValueFromClaimType(principal, JwtRegisteredClaimNames.NameId);

            if (string.IsNullOrEmpty(userId))
            {
                return(PandaResponse.CreateErrorResponse <RefreshTokenContract>("Invalid claim userId"));
            }

            var tokenValid = await _userLogic.ValidateRefreshToken(email, token.RefreshToken);

            if (tokenValid.IsError())
            {
                return(PandaResponse.CreateErrorResponse <RefreshTokenContract>(tokenValid.Errors.ToArray()));
            }

            var newJwtToken              = _jwtTokenService.GenerateToken(email, userId);
            var newRefreshToken          = _jwtTokenService.GenerateRefreshToken();
            var updateRefreshTokenResult = await _userLogic.UpdateRefreshTokenToUser(email, newRefreshToken);

            if (updateRefreshTokenResult.IsError())
            {
                return(PandaResponse.CreateErrorResponse <RefreshTokenContract>(updateRefreshTokenResult.Errors.ToArray()));
            }

            var result = PandaResponse.CreateSuccessResponse <RefreshTokenContract>(
                new RefreshTokenContract
            {
                Token        = newJwtToken,
                RefreshToken = newRefreshToken
            });

            return(result);
        }
Exemplo n.º 4
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));
        }
Exemplo n.º 5
0
        public RefreshTokenResult RefreshToken([FromBody] RefreshTokenContract contract)
        {
            ClaimsPrincipal сlaimsPrincipal = null;
            var             key             = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("authentification_security_key!qwe123"));

            try
            {
                сlaimsPrincipal = new JwtSecurityTokenHandler().ValidateToken(contract.AccessToken, new TokenValidationParameters
                {
                    ValidIssuer              = "VelevetechTestIssuer",
                    ValidAudience            = "VelevetechTest",
                    IssuerSigningKey         = key,
                    ValidateLifetime         = false,
                    ValidateIssuerSigningKey = true,
                    ClockSkew = TimeSpan.Zero
                }, out var securityToken);

                if (!(securityToken is JwtSecurityToken jwtSecurityToken) || !jwtSecurityToken.Header.Alg.Equals(SecurityAlgorithms.HmacSha256, StringComparison.InvariantCultureIgnoreCase))
                {
                    throw new SecurityTokenException("Invalid token");
                }
            }
            catch
            {
                // invalid token/signing key was passed and we can't extract user claims
                return(null);
            }

            var userIdStr = сlaimsPrincipal.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier)?.Value;
            var login     = сlaimsPrincipal.Claims.FirstOrDefault(c => c.Type == ClaimsIdentity.DefaultNameClaimType)?.Value;

            if (!Guid.TryParse(userIdStr, out Guid userId))
            {
                return(null);
            }

            var newRefreshToken = Guid.NewGuid();

            _authenticationService.UpdateRefreshToken(userId, contract.RefreshToken, newRefreshToken);

            var claims = new List <Claim>
            {
                new Claim(ClaimsIdentity.DefaultNameClaimType, login),
                new Claim(ClaimTypes.NameIdentifier, userId.ToString()),
            };
            var identity = new ClaimsIdentity(claims, "Token", ClaimsIdentity.DefaultNameClaimType, ClaimsIdentity.DefaultRoleClaimType);

            var now = DateTime.UtcNow;

            var jwt = new JwtSecurityToken(
                issuer: "VelevetechTestIssuer",
                audience: "VelevetechTest",
                notBefore: now,
                claims: identity.Claims,
                expires: now.Add(TimeSpan.FromMinutes(30)),
                signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256));
            var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);

            return(new RefreshTokenResult
            {
                AccessToken = encodedJwt,
                RefreshToken = newRefreshToken,
                ExpirationTime = DateTime.Now.AddMinutes(30),
            });
        }