elsa-core/src/modules/Elsa.Identity/Features/IdentityFeature.cs

78 lines
2.6 KiB
C#
Raw Normal View History

using Elsa.Common.Exceptions;
using Elsa.Common.Features;
using Elsa.Extensions;
using Elsa.Features.Abstractions;
using Elsa.Features.Attributes;
using Elsa.Features.Services;
using Elsa.Identity.Contracts;
using Elsa.Identity.Entities;
using Elsa.Identity.HostedServices;
using Elsa.Identity.Options;
using Elsa.Identity.Services;
using Microsoft.Extensions.DependencyInjection;
namespace Elsa.Identity.Features;
2022-11-23 10:20:35 +00:00
/// <summary>
/// Provides identity feature to authenticate & authorize API requests.
/// </summary>
[DependsOn(typeof(SystemClockFeature))]
public class IdentityFeature : FeatureBase
{
/// <inheritdoc />
public IdentityFeature(IModule module) : base(module)
{
}
/// <summary>
2023-01-01 21:54:07 +00:00
/// A delegate to configure <see cref="Options.IdentityOptions"/>.
/// </summary>
2023-01-01 21:54:07 +00:00
public IdentityOptions IdentityOptions { get; set; } = new();
/// <summary>
2023-01-01 21:54:07 +00:00
/// A delegate to configure <see cref="Options.IdentityTokenOptions"/>.
/// </summary>
2023-01-01 21:54:07 +00:00
public IdentityTokenOptions TokenOptions { get; set; } = new();
/// <summary>
/// A delegate that creates an instance of an implementation of <see cref="IUserStore"/>.
/// </summary>
public Func<IServiceProvider, IUserStore> UserStore { get; set; } = sp => sp.GetRequiredService<MemoryUserStore>();
/// <summary>
/// A delegate that creates an instance of an implementation of <see cref="IRoleStore"/>.
/// </summary>
public Func<IServiceProvider, IRoleStore> RoleStore { get; set; } = sp => sp.GetRequiredService<MemoryRoleStore>();
2022-12-09 12:44:36 +00:00
/// <inheritdoc />
public override void Configure()
{
Module.AddFastEndpointsAssembly(GetType());
}
/// <inheritdoc />
public override void ConfigureHostedServices()
{
2023-01-01 21:54:07 +00:00
if(IdentityOptions.CreateDefaultAdmin)
Module.ConfigureHostedService<SetupDefaultUserHostedService>();
}
/// <inheritdoc />
public override void Apply()
{
if (string.IsNullOrWhiteSpace(TokenOptions.SigningKey))
throw new MissingConfigurationException("SigningKey is a required setting for the Identity feature.");
2023-01-01 21:54:07 +00:00
Services.Configure<IdentityTokenOptions>(options => options.CopyFrom(TokenOptions));
Services
.AddMemoryStore<User, MemoryUserStore>()
.AddMemoryStore<Role, MemoryRoleStore>()
.AddSingleton(UserStore)
.AddSingleton(RoleStore)
.AddSingleton<IPasswordHasher, DefaultPasswordHasher>()
.AddSingleton<IAccessTokenIssuer, DefaultAccessTokenIssuer>()
.AddSingleton<ICredentialsValidator, DefaultCredentialsValidator>()
;
}
}