Beispiel #1
0
        public async Task <IHttpActionResult> RefreshToken([FromBody] string jwToken, string refreshToken)
        {
            var courierPrincipal = _authService.GetPrincipalFromToken(jwToken);

            var tokenActive = await _authService.IsTokenExistsAsync(jwToken);

            // invalid token/signing key was passed and we can't extract courier claims
            if (courierPrincipal == null || !tokenActive)
            {
                return(NotFound());
            }

            var id = courierPrincipal.Claims.First(c => c.Type == "id").Value;

            var courierId = Convert.ToInt32(id);

            var courier = await _refreshTokenService.GetByCourierAuthDataByIdAsync(courierId);

            if (courier == null ||
                courier.RefreshTokenIsActive != true ||
                courier.RefreshTokenIp != GetRemoteIp() ||
                courier.RefreshToken != refreshToken)
            {
                return(NotFound());
            }

            await _refreshTokenService.ClearAsync(courierId);

            // RefreshToken
            var newRefreshToken = GenerateTokenByRandomNumber();

            var refreshTokenDto = new RefreshTokenDto
            {
                IsActive = true,
                Token    = newRefreshToken,
                Expires  = DateTime.Now.AddDays(5),
                RemoteIp = GetRemoteIp()
            };

            await _refreshTokenService.SetAsync(refreshTokenDto, courierId);

            // JWToken
            var newJWToken = await _authService.GenerateJWTokenAsync(courierId);

            await _jwTokenService.SetAsync(courierId, newJWToken);

            var memCacher = new CustomMemoryCacher();

            if (memCacher.GetValue(jwToken) == null)
            {
                memCacher.Add(newJWToken, courier.Id, DateTimeOffset.UtcNow.AddHours(12));
            }

            var response = new LoginResponseDto()
            {
                AccessToken  = newJWToken,
                RefreshToken = newRefreshToken
            };

            return(Ok(response));
        }