Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,9 @@ ClientBindist
~$*
*~
*.dbmdl
Samples/RuntimeApps.Authentication.Sample/authentication.db
Samples/RuntimeApps.Authentication.Sample/authentication.db-shm
Samples/RuntimeApps.Authentication.Sample/authentication.db-wal
*.dbproj.schemaview
*.pfx
*.publishsettings
Expand Down Expand Up @@ -294,4 +297,4 @@ Thumbs.db

#angular
.angular/
.angular/cache/
.angular/cache/
42 changes: 26 additions & 16 deletions ReadMe.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,22 +54,12 @@ Add required services to DI:
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddRuntimeAppsAuthentication<IdentityUser, IdentityRole, string>()
.AddEfStores<ApplicationDbContext, IdentityUser, IdentityRole, string>()
.UseJwt(JwtBearerDefaults.AuthenticationScheme, option => {
SymmetricSecurityKey signingKey = new(Encoding.ASCII.GetBytes(builder.Configuration["Jwt:Key"]));
option.RequireHttpsMetadata = false;
option.SaveToken = true;
option.RefreshOnIssuerKeyNotFound = false;
option.TokenValidationParameters = new TokenValidationParameters {
ValidateIssuerSigningKey = true,
IssuerSigningKey = signingKey,
ValidateIssuer = false,
ValidIssuer = builder.Configuration["Jwt:Issuer"],
ValidateAudience = true,
ValidAudience = builder.Configuration["Jwt:Audience"],
ValidateLifetime = true,
ClockSkew = TimeSpan.Zero,
RequireExpirationTime = true,
};
.UseJwt(JwtBearerDefaults.AuthenticationScheme, builder.Configuration, option => {
var signingKey = builder.Configuration["Authentication:Jwt:SigningKey"]
?? throw new InvalidOperationException("Set Authentication:Jwt:SigningKey in user secrets or an environment variable.");
option.TokenValidationParameters.IssuerSigningKey =
new SymmetricSecurityKey(Encoding.UTF8.GetBytes(signingKey));
option.SaveToken = true; // Overrides Authentication:Jwt:SaveToken.
})
.AddValidators();
```
Expand Down Expand Up @@ -99,6 +89,26 @@ You can add more services and customize services. Also, there are some [samples]

## External Social Logins

### Explicit feature registration and configuration

`AddRuntimeAppsAuthentication<TUser, TRole, TKey>()` registers core Identity managers, the account service, and default user mappers only. Stores and optional features are registered explicitly. The existing `UseJwt`, `AddVerificationServices`, `AddForgotPassword`, `AddRefreshToken`, and provider methods remain available as fluent APIs.

Option sections are `Authentication:Jwt` (the existing `JwtBearerOptions` type), `Authentication:Verification`, `Authentication:ForgotPassword`, `Authentication:RefreshTokens`, and `Authentication:ExternalLogin:Google|Facebook|Microsoft`. Each feature supports configuration binding followed by an action callback. The callback runs after binding, so explicitly assigned values win while untouched values remain from configuration:

```cs
.AddVerificationServices(builder.Configuration)
.AddVerificationServices(options => options.CodeLength = 8)
.AddForgotPassword(builder.Configuration)
.AddRefreshToken(builder.Configuration, options => options.TokenLifetime = TimeSpan.FromDays(14))
.UseJwt(JwtBearerDefaults.AuthenticationScheme, builder.Configuration, options => options.RequireHttpsMetadata = true)
```

The JWT overload binds `Authentication:Jwt` to the selected scheme only. For example, appsettings can hold `SaveToken`, `RefreshInterval`, and `TokenValidationParameters` (such as issuer and audience settings), while the callback can set an unbindable `IssuerSigningKey` from user secrets or an environment variable. Keep the signing key out of committed JSON. The callback overrides only the properties it assigns.

Actions alone remain supported. Defaults are supplied by each options type; configuration binding runs before callbacks; standard Options post-configuration runs afterward; feature validation runs on application startup. External provider options bind JSON values while callbacks can set non-bindable mapper delegates. Keep credentials in user secrets, environment variables, or a secret manager.

Registrations use `TryAdd` to preserve application-provided services. Store interfaces for a single store implementation resolve the same scoped store instance. Use `AddUserMapper` to replace the selected mapper; register custom store interfaces before `AddStores` to retain your implementations. Repeating feature registration appends options configuration in call order and does not duplicate default provider/service registrations.

In many cases you want to add social login to your project, so users can quickly log in and use the application. External login needs to redirect the user to the social login pages which are not useful for API services. This repository provides an easy way to handle external login in ASP.Net core web API. You only should do:

In the frontend part, you could use various libraries based on what framework you are using. For example, you could use [Angular Social Login](https://www.npmjs.com/package/@abacritt/angularx-social-login) in angular and [react-social-login
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Hosting;
using RuntimeApps.Authentication.Features.Account.Services;
using RuntimeApps.Authentication.Features.ExternalLogin.Contracts;
using RuntimeApps.Authentication.Features.ExternalLogin.Models;
using RuntimeApps.Authentication.Features.ExternalLogin.Providers;
using RuntimeApps.Authentication.Features.ExternalLogin.Services;
using RuntimeApps.Authentication.Features.PasswordRecovery.Contracts;
using RuntimeApps.Authentication.Features.PasswordRecovery.Models;
using RuntimeApps.Authentication.Features.PasswordRecovery.Services;
using RuntimeApps.Authentication.Features.Registration.Contracts;
using RuntimeApps.Authentication.Features.Registration.Services;
using RuntimeApps.Authentication.Features.Verification.Contracts;
using RuntimeApps.Authentication.Features.Verification.Models;
using RuntimeApps.Authentication.Features.Verification.Services;
using RuntimeApps.Authentication.Identity.Contracts;

namespace RuntimeApps.Authentication.DependencyInjection {
/// <summary>Opt-in feature registrations. Each method only adds the named feature's services.</summary>
public static class FeatureRegistrationExtensions {
/// <summary>Registers Identity's standard validators if the application has not supplied validators.</summary>
public static RuntimeAppsAuthenticationBuilder<TUser, TRole, TKey> AddValidators<TUser, TRole, TKey>(this RuntimeAppsAuthenticationBuilder<TUser, TRole, TKey> builder, Action<IdentityOptions> configure = null)
where TUser : IdentityUser<TKey>, new() where TRole : IdentityRole<TKey> where TKey : IEquatable<TKey> {
ArgumentNullException.ThrowIfNull(builder);
builder.Services.TryAddTransient<IPasswordValidator<TUser>, PasswordValidator<TUser>>();
builder.Services.TryAddTransient<IUserValidator<TUser>, UserValidator<TUser>>();
builder.Services.TryAddTransient<IRoleValidator<TRole>, RoleValidator<TRole>>();
if (configure != null) builder.Services.Configure(configure);
return builder;
}
public static RuntimeAppsAuthenticationBuilder<TUser, TRole, TKey> AddVerificationServices<TUser, TRole, TKey>(this RuntimeAppsAuthenticationBuilder<TUser, TRole, TKey> builder, IConfiguration configuration)
where TUser : IdentityUser<TKey>, new() where TRole : IdentityRole<TKey> where TKey : IEquatable<TKey> =>
AddVerificationServices(builder, configuration, null);

public static RuntimeAppsAuthenticationBuilder<TUser, TRole, TKey> AddVerificationServices<TUser, TRole, TKey>(this RuntimeAppsAuthenticationBuilder<TUser, TRole, TKey> builder, Action<VerificationOptions> configureOptions = null)
where TUser : IdentityUser<TKey>, new() where TRole : IdentityRole<TKey> where TKey : IEquatable<TKey> =>
AddVerificationServices(builder, null, configureOptions);

private static RuntimeAppsAuthenticationBuilder<TUser, TRole, TKey> AddVerificationServices<TUser, TRole, TKey>(RuntimeAppsAuthenticationBuilder<TUser, TRole, TKey> builder, IConfiguration configuration, Action<VerificationOptions> configure)
where TUser : IdentityUser<TKey>, new() where TRole : IdentityRole<TKey> where TKey : IEquatable<TKey> {
ArgumentNullException.ThrowIfNull(builder);
var options = builder.Services.AddOptions<VerificationOptions>();
if (configuration != null) options.Bind(configuration.GetSection(VerificationOptions.SectionName));
if (configure != null) options.Configure(configure);
options.Validate(o => { try { o.Validate(); return true; } catch (InvalidOperationException) { return false; } }, "Verification options are invalid. Check code length, lifetime, attempt count, cooldown, and send limit.").ValidateOnStart();
builder.Services.AddDataProtection();
builder.Services.Configure<IdentityOptions>(o => o.SignIn.RequireConfirmedEmail = true);
builder.Services.TryAddSingleton(TimeProvider.System);
builder.Services.TryAddScoped<IVerificationCodeGenerator<TUser, TKey>, RandomVerificationCodeGenerator<TUser, TKey>>();
builder.Services.TryAddScoped<IVerificationCodeVerifier<TKey>, DataProtectionVerificationCodeVerifier<TKey>>();
builder.Services.TryAddScoped<IVerificationWorkflowService<TUser, TKey>, VerificationWorkflowService<TUser, TKey>>();
builder.Services.TryAddScoped<IForgotPasswordVerificationWorkflow<TUser, TKey>, VerificationWorkflowService<TUser, TKey>>();
builder.Services.TryAddScoped<IRegistrationService<TUser, TKey>, RegistrationService<TUser, TKey>>();
builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton<IHostedService, VerificationDependenciesStartupValidator<TUser, TKey>>());
return builder;
}

public static RuntimeAppsAuthenticationBuilder<TUser, TRole, TKey> AddForgotPassword<TUser, TRole, TKey>(this RuntimeAppsAuthenticationBuilder<TUser, TRole, TKey> builder, IConfiguration configuration)
where TUser : IdentityUser<TKey>, new() where TRole : IdentityRole<TKey> where TKey : IEquatable<TKey> => AddForgotPasswordCore(builder, configuration, null);
public static RuntimeAppsAuthenticationBuilder<TUser, TRole, TKey> AddForgotPassword<TUser, TRole, TKey>(this RuntimeAppsAuthenticationBuilder<TUser, TRole, TKey> builder, IConfiguration configuration, Action<ForgotPasswordOptions> configureOptions)
where TUser : IdentityUser<TKey>, new() where TRole : IdentityRole<TKey> where TKey : IEquatable<TKey> => AddForgotPasswordCore(builder, configuration, configureOptions);
public static RuntimeAppsAuthenticationBuilder<TUser, TRole, TKey> AddForgotPassword<TUser, TRole, TKey>(this RuntimeAppsAuthenticationBuilder<TUser, TRole, TKey> builder, Action<ForgotPasswordOptions> configureOptions = null)
where TUser : IdentityUser<TKey>, new() where TRole : IdentityRole<TKey> where TKey : IEquatable<TKey> => AddForgotPasswordCore(builder, null, configureOptions);
private static RuntimeAppsAuthenticationBuilder<TUser, TRole, TKey> AddForgotPasswordCore<TUser, TRole, TKey>(RuntimeAppsAuthenticationBuilder<TUser, TRole, TKey> builder, IConfiguration configuration, Action<ForgotPasswordOptions> configure)
where TUser : IdentityUser<TKey>, new() where TRole : IdentityRole<TKey> where TKey : IEquatable<TKey> {
ArgumentNullException.ThrowIfNull(builder);
var options = builder.Services.AddOptions<ForgotPasswordOptions>();
if (configuration != null) options.Bind(configuration.GetSection(ForgotPasswordOptions.SectionName));
if (configure != null) options.Configure(configure);
options.Validate(o => { try { o.Validate(); return true; } catch (InvalidOperationException) { return false; } }, "Forgot-password options are invalid. Link mode requires an absolute HTTPS FrontendResetUrl.").ValidateOnStart();
builder.Services.TryAddTransient<DataProtectorTokenProvider<TUser>>();
builder.Services.Configure<IdentityOptions>(o => o.Tokens.ProviderMap.TryAdd(TokenOptions.DefaultProvider, new TokenProviderDescriptor(typeof(DataProtectorTokenProvider<TUser>))));
builder.Services.TryAddScoped<IForgotPasswordService<TUser, TKey>, ForgotPasswordService<TUser, TKey>>();
builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton<IHostedService, VerificationDependenciesStartupValidator<TUser, TKey>>());
return builder;
}

public static RuntimeAppsAuthenticationBuilder<TUser, TRole, TKey> UseJwt<TUser, TRole, TKey>(this RuntimeAppsAuthenticationBuilder<TUser, TRole, TKey> builder, string scheme, Action<JwtBearerOptions> configure)
where TUser : IdentityUser<TKey>, new() where TRole : IdentityRole<TKey> where TKey : IEquatable<TKey> {
ArgumentNullException.ThrowIfNull(builder); ArgumentNullException.ThrowIfNull(configure);
builder.Services.AddOptions<JwtBearerOptions>(scheme).ValidateOnStart();
builder.Authentication.AddJwtBearer(scheme, configure);
AddJwtProvider<TUser, TRole, TKey>(builder, scheme);
return builder;
}

public static RuntimeAppsAuthenticationBuilder<TUser, TRole, TKey> UseJwt<TUser, TRole, TKey>(this RuntimeAppsAuthenticationBuilder<TUser, TRole, TKey> builder, string scheme, IConfiguration configuration, Action<JwtBearerOptions> configure = null)
where TUser : IdentityUser<TKey>, new() where TRole : IdentityRole<TKey> where TKey : IEquatable<TKey> {
ArgumentNullException.ThrowIfNull(builder); ArgumentNullException.ThrowIfNull(configuration);
const string section = "Authentication:Jwt";
builder.Authentication.AddJwtBearer(scheme);
var schemeOptions = builder.Services.AddOptions<JwtBearerOptions>(scheme).Bind(configuration.GetSection(section));
if (configure != null) schemeOptions.Configure(configure);
schemeOptions.ValidateOnStart();
AddJwtProvider<TUser, TRole, TKey>(builder, scheme);
return builder;
}

private static void AddJwtProvider<TUser, TRole, TKey>(RuntimeAppsAuthenticationBuilder<TUser, TRole, TKey> builder, string scheme)
where TUser : IdentityUser<TKey>, new() where TRole : IdentityRole<TKey> where TKey : IEquatable<TKey> =>
builder.Services.TryAddScoped<IJwtProvider<TUser>>(services => new JwtProvider<TUser, TKey>(
services.GetRequiredService<Microsoft.Extensions.Options.IOptionsMonitor<JwtBearerOptions>>().Get(scheme),
services.GetRequiredService<Microsoft.AspNetCore.Identity.IUserClaimsPrincipalFactory<TUser>>()));

private static RuntimeAppsAuthenticationBuilder<TUser, TRole, TKey> AddProvider<TUser, TRole, TKey, TOption, TProvider>(RuntimeAppsAuthenticationBuilder<TUser, TRole, TKey> b, IConfiguration c, Action<TOption> configure)
where TUser : IdentityUser<TKey>, new() where TRole : IdentityRole<TKey> where TKey : IEquatable<TKey>
where TOption : BaseExternalLoginOption, new() where TProvider : class, IExternalLoginProvider<TUser> {
ArgumentNullException.ThrowIfNull(b);
var o = b.Services.AddOptions<TOption>();
if (c != null) o.Bind(c.GetSection(TOptionSection<TOption>.Name));
if (configure != null) o.Configure(configure);
o.Validate(x => !string.IsNullOrWhiteSpace(x.ClientId) && !string.IsNullOrWhiteSpace(x.ClientSecret), "External login requires ClientId and ClientSecret.").ValidateOnStart();
b.Services.TryAddEnumerable(ServiceDescriptor.Transient<IExternalLoginProvider<TUser>, TProvider>());
b.Services.TryAddScoped<IExternalLoginEmailTrustPolicy<TUser>, DefaultExternalLoginEmailTrustPolicy<TUser>>();
return b;
}
private static class TOptionSection<T> { public static string Name => typeof(T).Name.StartsWith("Google", StringComparison.Ordinal) ? "Authentication:ExternalLogin:Google" : typeof(T).Name.StartsWith("Facebook", StringComparison.Ordinal) ? "Authentication:ExternalLogin:Facebook" : "Authentication:ExternalLogin:Microsoft"; }
public static RuntimeAppsAuthenticationBuilder<TUser, TRole, TKey> AddGoogleExternalLogin<TUser, TRole, TKey>(this RuntimeAppsAuthenticationBuilder<TUser, TRole, TKey> b, Action<GoogleExternalLoginOption<TUser>> configure) where TUser : IdentityUser<TKey>, new() where TRole : IdentityRole<TKey> where TKey : IEquatable<TKey> => AddProvider<TUser, TRole, TKey, GoogleExternalLoginOption<TUser>, GoogleExternalLoginProvider<TUser>>(b, null, configure);
public static RuntimeAppsAuthenticationBuilder<TUser, TRole, TKey> AddGoogleExternalLogin<TUser, TRole, TKey>(this RuntimeAppsAuthenticationBuilder<TUser, TRole, TKey> b, IConfiguration c, Action<GoogleExternalLoginOption<TUser>> configure = null) where TUser : IdentityUser<TKey>, new() where TRole : IdentityRole<TKey> where TKey : IEquatable<TKey> => AddProvider<TUser, TRole, TKey, GoogleExternalLoginOption<TUser>, GoogleExternalLoginProvider<TUser>>(b, c, configure);
public static RuntimeAppsAuthenticationBuilder<TUser, TRole, TKey> AddFacebookExternalLogin<TUser, TRole, TKey>(this RuntimeAppsAuthenticationBuilder<TUser, TRole, TKey> b, Action<FacebookExternalLoginOption<TUser>> configure) where TUser : IdentityUser<TKey>, new() where TRole : IdentityRole<TKey> where TKey : IEquatable<TKey> => AddProvider<TUser, TRole, TKey, FacebookExternalLoginOption<TUser>, FacebookExternalLoginProvider<TUser>>(b, null, configure);
public static RuntimeAppsAuthenticationBuilder<TUser, TRole, TKey> AddFacebookExternalLogin<TUser, TRole, TKey>(this RuntimeAppsAuthenticationBuilder<TUser, TRole, TKey> b, IConfiguration c, Action<FacebookExternalLoginOption<TUser>> configure = null) where TUser : IdentityUser<TKey>, new() where TRole : IdentityRole<TKey> where TKey : IEquatable<TKey> => AddProvider<TUser, TRole, TKey, FacebookExternalLoginOption<TUser>, FacebookExternalLoginProvider<TUser>>(b, c, configure);
public static RuntimeAppsAuthenticationBuilder<TUser, TRole, TKey> AddMicrosoftExternalLogin<TUser, TRole, TKey>(this RuntimeAppsAuthenticationBuilder<TUser, TRole, TKey> b, Action<MicrosoftExternalLoginOption<TUser>> configure) where TUser : IdentityUser<TKey>, new() where TRole : IdentityRole<TKey> where TKey : IEquatable<TKey> => AddProvider<TUser, TRole, TKey, MicrosoftExternalLoginOption<TUser>, MicrosoftExternalLoginProvider<TUser>>(b, null, configure);
public static RuntimeAppsAuthenticationBuilder<TUser, TRole, TKey> AddMicrosoftExternalLogin<TUser, TRole, TKey>(this RuntimeAppsAuthenticationBuilder<TUser, TRole, TKey> b, IConfiguration c, Action<MicrosoftExternalLoginOption<TUser>> configure = null) where TUser : IdentityUser<TKey>, new() where TRole : IdentityRole<TKey> where TKey : IEquatable<TKey> => AddProvider<TUser, TRole, TKey, MicrosoftExternalLoginOption<TUser>, MicrosoftExternalLoginProvider<TUser>>(b, c, configure);
}
}
Loading
Loading