| | | 1 | | using System.Security.Claims; |
| | | 2 | | using AspNetCore.Authentication.ApiKey; |
| | | 3 | | using Elsa.Identity.Contracts; |
| | | 4 | | using Elsa.Identity.Models; |
| | | 5 | | |
| | | 6 | | namespace Elsa.Identity.Providers; |
| | | 7 | | |
| | | 8 | | /// <summary> |
| | | 9 | | /// Validates a given API key and returns an instance of <see cref="IApiKey"/> if the key is valid. |
| | | 10 | | /// </summary> |
| | | 11 | | public class DefaultApiKeyProvider : IApiKeyProvider |
| | | 12 | | { |
| | | 13 | | private readonly IApplicationCredentialsValidator _applicationCredentialsValidator; |
| | | 14 | | private readonly IRoleProvider _roleProvider; |
| | | 15 | | |
| | | 16 | | /// <summary> |
| | | 17 | | /// Initializes a new instance of the <see cref="DefaultApiKeyProvider"/> class. |
| | | 18 | | /// </summary> |
| | 0 | 19 | | public DefaultApiKeyProvider(IApplicationCredentialsValidator applicationCredentialsValidator, IRoleProvider rolePro |
| | | 20 | | { |
| | 0 | 21 | | _applicationCredentialsValidator = applicationCredentialsValidator; |
| | 0 | 22 | | _roleProvider = roleProvider; |
| | 0 | 23 | | } |
| | | 24 | | |
| | | 25 | | /// <summary> |
| | | 26 | | /// Gets an instance of <see cref="IApiKey"/>. |
| | | 27 | | /// </summary> |
| | | 28 | | /// <param name="key">The API key to validate.</param> |
| | | 29 | | /// <returns>The API key if a valid key was provided.</returns> |
| | | 30 | | public async Task<IApiKey?> ProvideAsync(string key) |
| | | 31 | | { |
| | 0 | 32 | | var application = await _applicationCredentialsValidator.ValidateAsync(key); |
| | | 33 | | |
| | 0 | 34 | | if (application == null) |
| | 0 | 35 | | return null; |
| | | 36 | | |
| | 0 | 37 | | var filter = new RoleFilter { Ids = application.Roles.Distinct().ToList() }; |
| | 0 | 38 | | var roles = (await _roleProvider.FindManyAsync(filter)).ToList(); |
| | 0 | 39 | | var permissions = roles.SelectMany(x => x.Permissions).Distinct().ToList(); |
| | 0 | 40 | | var claims = new List<Claim>(); |
| | | 41 | | |
| | 0 | 42 | | claims.AddRange(permissions.Select(p => new Claim("permissions", p))); |
| | | 43 | | |
| | 0 | 44 | | return new ApiKey(key, application.ClientId, claims); |
| | 0 | 45 | | } |
| | | 46 | | } |