2023-03-26 21:53:17 +00:00
|
|
|
using Elsa.Extensions;
|
|
|
|
|
using Elsa.Identity.Contracts;
|
|
|
|
|
using Elsa.Identity.Entities;
|
|
|
|
|
using JetBrains.Annotations;
|
|
|
|
|
|
|
|
|
|
namespace Elsa.Identity.Services;
|
|
|
|
|
|
|
|
|
|
/// <inheritdoc />
|
|
|
|
|
[PublicAPI]
|
|
|
|
|
public class DefaultApplicationCredentialsValidator : IApplicationCredentialsValidator
|
|
|
|
|
{
|
|
|
|
|
private readonly IApiKeyParser _apiKeyParser;
|
|
|
|
|
private readonly IApplicationProvider _applicationProvider;
|
2026-05-20 11:20:46 +00:00
|
|
|
private readonly IApplicationStore _applicationStore;
|
2023-03-26 21:53:17 +00:00
|
|
|
private readonly ISecretHasher _secretHasher;
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// Initializes a new instance of the <see cref="DefaultApplicationCredentialsValidator"/> class.
|
|
|
|
|
/// </summary>
|
2026-05-20 11:20:46 +00:00
|
|
|
public DefaultApplicationCredentialsValidator(IApiKeyParser apiKeyParser, IApplicationProvider applicationProvider, IApplicationStore applicationStore, ISecretHasher secretHasher)
|
2023-03-26 21:53:17 +00:00
|
|
|
{
|
|
|
|
|
_apiKeyParser = apiKeyParser;
|
|
|
|
|
_applicationProvider = applicationProvider;
|
2026-05-20 11:20:46 +00:00
|
|
|
_applicationStore = applicationStore;
|
2023-03-26 21:53:17 +00:00
|
|
|
_secretHasher = secretHasher;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// <inheritdoc />
|
|
|
|
|
public async ValueTask<Application?> ValidateAsync(string apiKey, CancellationToken cancellationToken = default)
|
|
|
|
|
{
|
2023-08-11 09:34:50 +00:00
|
|
|
if(string.IsNullOrWhiteSpace(apiKey))
|
2025-06-02 19:52:10 +00:00
|
|
|
return null;
|
2023-08-11 09:34:50 +00:00
|
|
|
|
2023-03-26 21:53:17 +00:00
|
|
|
var clientId = _apiKeyParser.Parse(apiKey);
|
|
|
|
|
var application = await _applicationProvider.FindByClientIdAsync(clientId, cancellationToken);
|
|
|
|
|
|
|
|
|
|
if(application == null)
|
2025-06-02 19:52:10 +00:00
|
|
|
return null;
|
2023-03-26 21:53:17 +00:00
|
|
|
|
2026-05-20 11:20:46 +00:00
|
|
|
var isValidApiKey = _secretHasher.VerifySecret(apiKey, application.HashedApiKey, application.HashedApiKeySalt, out var needsRehash);
|
|
|
|
|
|
|
|
|
|
if (!isValidApiKey)
|
|
|
|
|
return null;
|
|
|
|
|
|
|
|
|
|
if (needsRehash)
|
|
|
|
|
{
|
|
|
|
|
var hashedApiKey = _secretHasher.HashSecret(apiKey);
|
|
|
|
|
application.HashedApiKey = hashedApiKey.EncodeSecret();
|
|
|
|
|
application.HashedApiKeySalt = hashedApiKey.EncodeSalt();
|
|
|
|
|
await _applicationStore.SaveAsync(application, cancellationToken);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return application;
|
2023-03-26 21:53:17 +00:00
|
|
|
}
|
2026-05-20 11:20:46 +00:00
|
|
|
}
|