2023-03-26 21:53:17 +00:00
|
|
|
using AspNetCore.Authentication.ApiKey;
|
|
|
|
|
using Elsa.Extensions;
|
2022-12-30 12:11:29 +00:00
|
|
|
using Elsa.Features.Abstractions;
|
|
|
|
|
using Elsa.Features.Attributes;
|
|
|
|
|
using Elsa.Features.Services;
|
2023-03-26 21:53:17 +00:00
|
|
|
using Elsa.Identity.Providers;
|
2023-01-05 12:55:08 +00:00
|
|
|
using Elsa.Requirements;
|
2022-12-30 12:11:29 +00:00
|
|
|
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
2023-01-05 12:55:08 +00:00
|
|
|
using Microsoft.AspNetCore.Authorization;
|
2022-12-30 12:11:29 +00:00
|
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
|
|
|
|
|
|
|
|
namespace Elsa.Identity.Features;
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
2023-03-26 21:53:17 +00:00
|
|
|
/// Provides an authorization feature that configures the system with JWT bearer and API key authentication.
|
2022-12-30 12:11:29 +00:00
|
|
|
/// </summary>
|
|
|
|
|
[DependsOn(typeof(IdentityFeature))]
|
|
|
|
|
public class DefaultAuthenticationFeature : FeatureBase
|
|
|
|
|
{
|
2023-03-26 21:53:17 +00:00
|
|
|
private const string MultiScheme = "Jwt-or-ApiKey";
|
|
|
|
|
|
2022-12-30 12:11:29 +00:00
|
|
|
/// <inheritdoc />
|
|
|
|
|
public DefaultAuthenticationFeature(IModule module) : base(module)
|
|
|
|
|
{
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// <inheritdoc />
|
|
|
|
|
public override void Apply()
|
|
|
|
|
{
|
2023-03-26 21:53:17 +00:00
|
|
|
Services.ConfigureOptions<ConfigureJwtBearerOptions>();
|
|
|
|
|
Services.ConfigureOptions<ValidateIdentityTokenOptions>();
|
|
|
|
|
|
2022-12-30 12:11:29 +00:00
|
|
|
Services
|
2023-03-26 21:53:17 +00:00
|
|
|
.AddAuthentication(MultiScheme)
|
|
|
|
|
.AddPolicyScheme(MultiScheme, MultiScheme, options =>
|
|
|
|
|
{
|
|
|
|
|
options.ForwardDefaultSelector = context =>
|
|
|
|
|
{
|
|
|
|
|
return context.Request.Headers.Authorization.Any(x => x!.Contains(ApiKeyDefaults.AuthenticationScheme))
|
|
|
|
|
? ApiKeyDefaults.AuthenticationScheme
|
|
|
|
|
: JwtBearerDefaults.AuthenticationScheme;
|
|
|
|
|
};
|
|
|
|
|
})
|
|
|
|
|
.AddJwtBearer()
|
|
|
|
|
.AddApiKeyInAuthorizationHeader<DefaultApiKeyProvider>();
|
|
|
|
|
|
2023-01-05 12:55:08 +00:00
|
|
|
Services.AddSingleton<IAuthorizationHandler, LocalHostRequirementHandler>();
|
2023-03-26 21:53:17 +00:00
|
|
|
Services.AddAuthorization(options => options.AddPolicy(IdentityPolicyNames.SecurityRoot, policy => policy.AddRequirements(new LocalHostRequirement())));
|
|
|
|
|
}
|
2022-12-30 12:11:29 +00:00
|
|
|
}
|