| | | 1 | | using Elsa.Common.Multitenancy; |
| | | 2 | | using Elsa.Identity.Constants; |
| | | 3 | | using Elsa.Identity.Contracts; |
| | | 4 | | using Elsa.Identity.Models; |
| | | 5 | | using Elsa.Identity.Options; |
| | | 6 | | using Microsoft.Extensions.Options; |
| | | 7 | | using Microsoft.IdentityModel.JsonWebTokens; |
| | | 8 | | |
| | | 9 | | namespace Elsa.Identity.Services; |
| | | 10 | | |
| | | 11 | | /// <summary> |
| | | 12 | | /// Validates and exchanges Elsa identity refresh tokens. |
| | | 13 | | /// </summary> |
| | 1 | 14 | | public sealed class DefaultIdentityRefreshTokenService( |
| | 1 | 15 | | IUserProvider userProvider, |
| | 1 | 16 | | IAccessTokenIssuer accessTokenIssuer, |
| | 1 | 17 | | ITenantAccessor tenantAccessor, |
| | 1 | 18 | | IOptions<IdentityTokenOptions> identityTokenOptions) : IIdentityRefreshTokenService |
| | | 19 | | { |
| | | 20 | | /// <inheritdoc /> |
| | | 21 | | public async ValueTask<IssuedTokens?> RefreshAsync(string refreshToken, CancellationToken cancellationToken = defaul |
| | | 22 | | { |
| | 2 | 23 | | if (string.IsNullOrWhiteSpace(refreshToken)) |
| | 0 | 24 | | return null; |
| | | 25 | | |
| | 2 | 26 | | var options = identityTokenOptions.Value; |
| | 2 | 27 | | var validationResult = await new JsonWebTokenHandler().ValidateTokenAsync(refreshToken, options.CreateTokenValid |
| | | 28 | | |
| | 2 | 29 | | if (!validationResult.IsValid) |
| | 0 | 30 | | return null; |
| | | 31 | | |
| | 2 | 32 | | var identity = validationResult.ClaimsIdentity; |
| | 2 | 33 | | var tokenUse = identity.FindFirst(TokenUse.ClaimType)?.Value; |
| | | 34 | | |
| | 2 | 35 | | if (!string.Equals(tokenUse, TokenUse.Refresh, StringComparison.Ordinal)) |
| | 1 | 36 | | return null; |
| | | 37 | | |
| | 1 | 38 | | var userId = identity.FindFirst(JwtRegisteredClaimNames.Sub)?.Value; |
| | 1 | 39 | | var userName = identity.FindFirst(JwtRegisteredClaimNames.Name)?.Value; |
| | | 40 | | |
| | 1 | 41 | | if (string.IsNullOrWhiteSpace(userId) && string.IsNullOrWhiteSpace(userName)) |
| | 0 | 42 | | return null; |
| | | 43 | | |
| | 1 | 44 | | var tenantId = identity.FindFirst(options.TenantIdClaimsType)?.Value; |
| | 1 | 45 | | var tenant = string.IsNullOrWhiteSpace(tenantId) ? null : new Tenant { Id = tenantId, Name = tenantId }; |
| | 1 | 46 | | using var tenantContext = tenantAccessor.PushContext(tenant); |
| | 1 | 47 | | var userFilter = string.IsNullOrWhiteSpace(userId) |
| | 1 | 48 | | ? new UserFilter { Name = userName } |
| | 1 | 49 | | : new UserFilter { Id = userId }; |
| | 1 | 50 | | var user = await userProvider.FindAsync(userFilter, cancellationToken); |
| | | 51 | | |
| | 1 | 52 | | return user is null ? null : await accessTokenIssuer.IssueTokensAsync(user, cancellationToken); |
| | 2 | 53 | | } |
| | | 54 | | } |