Permalink
Cannot retrieve contributors at this time
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
AspNetCoreApiStarter/src/Web.Api.Core/UseCases/ExchangeRefreshTokenUseCase.cs
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
55 lines (48 sloc)
2.34 KB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Linq; | |
using System.Threading.Tasks; | |
using Web.Api.Core.Dto.UseCaseRequests; | |
using Web.Api.Core.Dto.UseCaseResponses; | |
using Web.Api.Core.Interfaces; | |
using Web.Api.Core.Interfaces.Gateways.Repositories; | |
using Web.Api.Core.Interfaces.Services; | |
using Web.Api.Core.Interfaces.UseCases; | |
using Web.Api.Core.Specifications; | |
namespace Web.Api.Core.UseCases | |
{ | |
public sealed class ExchangeRefreshTokenUseCase : IExchangeRefreshTokenUseCase | |
{ | |
private readonly IJwtTokenValidator _jwtTokenValidator; | |
private readonly IUserRepository _userRepository; | |
private readonly IJwtFactory _jwtFactory; | |
private readonly ITokenFactory _tokenFactory; | |
public ExchangeRefreshTokenUseCase(IJwtTokenValidator jwtTokenValidator, IUserRepository userRepository, IJwtFactory jwtFactory, ITokenFactory tokenFactory) | |
{ | |
_jwtTokenValidator = jwtTokenValidator; | |
_userRepository = userRepository; | |
_jwtFactory = jwtFactory; | |
_tokenFactory = tokenFactory; | |
} | |
public async Task<bool> Handle(ExchangeRefreshTokenRequest message, IOutputPort<ExchangeRefreshTokenResponse> outputPort) | |
{ | |
var cp = _jwtTokenValidator.GetPrincipalFromToken(message.AccessToken, message.SigningKey); | |
// invalid token/signing key was passed and we can't extract user claims | |
if (cp != null) | |
{ | |
var id = cp.Claims.First(c => c.Type == "id"); | |
var user = await _userRepository.GetSingleBySpec(new UserSpecification(id.Value)); | |
if (user.HasValidRefreshToken(message.RefreshToken)) | |
{ | |
var jwtToken = await _jwtFactory.GenerateEncodedToken(user.IdentityId, user.UserName); | |
var refreshToken = _tokenFactory.GenerateToken(); | |
user.RemoveRefreshToken(message.RefreshToken); // delete the token we've exchanged | |
user.AddRefreshToken(refreshToken, user.Id, ""); // add the new one | |
await _userRepository.Update(user); | |
outputPort.Handle(new ExchangeRefreshTokenResponse(jwtToken, refreshToken, true)); | |
return true; | |
} | |
} | |
outputPort.Handle(new ExchangeRefreshTokenResponse(false, "Invalid token.")); | |
return false; | |
} | |
} | |
} |