Class AuthenticationExtensions
- Namespace
- Arc4u.OAuth2.Extensions
- Assembly
- Arc4u.OAuth2.AspNetCore.Authentication.dll
Extension methods that register the Arc4u authentication schemes: OpenID Connect with cookies
(AddOidcAuthentication), JWT bearer (AddJwtAuthentication) and both together (AddHybridAuthentication).
public static class AuthenticationExtensions
- Inheritance
-
AuthenticationExtensions
- Inherited Members
Methods
AddHybridAuthentication(IServiceCollection, IConfiguration, string, IX509CertificateLoader?)
Registers the hybrid authentication from the configuration. It does what
AddOidcAuthentication(IServiceCollection, IConfiguration, string, IX509CertificateLoader?) does and, in addition, reads the JWT bearer settings from the section
of OAuth2SettingsSectionPath (Authentication:OAuth2.Settings by default) and the optional Basic authentication settings from
BasicAuthenticationSectionPath (Authentication:Basic by default).
public static AuthenticationBuilder AddHybridAuthentication(this IServiceCollection services, IConfiguration configuration, string authenticationSectionName = "Authentication", IX509CertificateLoader? certificateLoader = null)
Parameters
servicesIServiceCollectionThe service collection.
configurationIConfigurationThe configuration.
authenticationSectionNamestringThe section bound to HybridAuthenticationSectionOptions. The default is
Authentication.certificateLoaderIX509CertificateLoaderThe loader of the certificates. When null, a default
X509CertificateLoaderis used.
Returns
- AuthenticationBuilder
The AuthenticationBuilder, to chain calls.
Examples
builder.Services.AddHybridAuthentication(builder.Configuration);
// ...
app.UseAuthentication();
app.UseAuthorization();
Remarks
In addition to the configuration required by AddOidcAuthentication, the OAuth2 settings (Authentication:OAuth2.Settings) are mandatory and must contain at least one audience,
unless ValidateAudience is false in that section. A minimal configuration:
{
"Application.configuration": { "ApplicationName": "MyApp" },
"Authentication": {
"DefaultAuthority": { "Url": "https://login.example.com/tenant/v2.0" },
"CookieName": ".MyApp.Cookies",
"OpenId.Settings": {
"ClientId": "my-client-id",
"ClientSecret": "my-client-secret",
"Audiences": [ "my-client-id" ],
"Scopes": [ "openid", "profile" ]
},
"OAuth2.Settings": { "Audiences": [ "api://my-api" ] },
"DataProtection": {
"EncryptionCertificate": { "Store": { "Name": "MyAppCertificate" } },
"CacheStore": { "CacheKey": "DataProtection", "CacheName": "Default" }
},
"TokenCache": { "CacheName": "Default" }
}
}
Exceptions
- ConfigurationException
The section does not exist, a mandatory value is missing, or the OAuth2 settings have no audience while
ValidateAudienceis true (the default).- MissingFieldException
A certificate cannot be found from its configuration section, or the OpenID settings have no client id, no scope, or no audience while
ValidateAudienceis true.
AddHybridAuthentication(IServiceCollection, Action<HybridAuthenticationOptions>)
Registers the hybrid authentication, from code: OpenID Connect with cookies for browser requests, and JWT bearer for requests that carry an Authorization: Bearer header.
The Arc4uScheme policy scheme selects the JWT bearer scheme when the header starts with Bearer and the OpenID Connect scheme otherwise.
public static AuthenticationBuilder AddHybridAuthentication(this IServiceCollection services, Action<HybridAuthenticationOptions> authenticationOptions)
Parameters
servicesIServiceCollectionThe service collection.
authenticationOptionsAction<HybridAuthenticationOptions>The action that configures the HybridAuthenticationOptions. OAuth2SettingsOptions is required in addition to the required OidcAuthenticationOptions members.
Returns
- AuthenticationBuilder
The AuthenticationBuilder, to chain calls.
Exceptions
- ArgumentNullException
An argument or a required option is null.
AddJwtAuthentication(IServiceCollection, IConfiguration, Action<JwtAuthenticationOptions>)
Registers the JWT bearer authentication from code. It is meant for an API only scenario.
Tokens are validated against the default authority (the issuer is not validated) with the audiences of the OAuth2SettingsOption, and the raw token is kept in the BootstrapContext of the identity.
public static AuthenticationBuilder AddJwtAuthentication(this IServiceCollection services, IConfiguration configuration, Action<JwtAuthenticationOptions> authenticationOptions)
Parameters
servicesIServiceCollectionThe service collection.
configurationIConfigurationThe configuration. It is not used by this overload.
authenticationOptionsAction<JwtAuthenticationOptions>The action that configures the JwtAuthenticationOptions. OAuth2SettingsOptions is required.
Returns
- AuthenticationBuilder
The AuthenticationBuilder, to chain calls.
Exceptions
- ArgumentNullException
An argument or OAuth2SettingsOptions is null.
AddJwtAuthentication(IServiceCollection, IConfiguration, string, IX509CertificateLoader?)
Registers the JWT bearer authentication from the configuration. It is meant for an API only scenario.
public static AuthenticationBuilder AddJwtAuthentication(this IServiceCollection services, IConfiguration configuration, string authenticationSectionName = "Authentication", IX509CertificateLoader? certificateLoader = null)
Parameters
servicesIServiceCollectionThe service collection.
configurationIConfigurationThe configuration.
authenticationSectionNamestringThe section bound to JwtAuthenticationSectionOptions. The default is
Authentication.certificateLoaderIX509CertificateLoaderThe loader of the certificates. When null, a default
X509CertificateLoaderis used.
Returns
- AuthenticationBuilder
The AuthenticationBuilder, to chain calls.
Examples
builder.Services.AddJwtAuthentication(builder.Configuration);
// ...
app.UseAuthentication();
app.UseAuthorization();
Remarks
Besides the JWT bearer scheme, the method registers, from the sections named by JwtAuthenticationSectionOptions: the OAuth2 settings, the claim identifiers, the domain mappings, the token cache,
the claims filler, the client tokens (Authentication:ClientTokens) and the remote secrets (Authentication:RemoteSecrets).
The token cache section (Authentication:TokenCache) is optional: an API that only validates inbound tokens can omit it, and the default cache is then used.
User.Identity.Name is read from the NameClaimType claim (name by default).
A minimal configuration:
{
"Authentication": {
"DefaultAuthority": { "Url": "https://login.example.com/tenant/v2.0" },
"OAuth2.Settings": {
"Audiences": [ "api://my-api" ]
}
}
}
Exceptions
- InvalidOperationException
The section does not exist.
- MissingFieldException
The default authority or the OAuth2 settings section path is missing, or the certificate cannot be found.
AddOidcAuthentication(IServiceCollection, IConfiguration, string, IX509CertificateLoader?)
Registers the OpenID Connect authentication with cookies from the configuration.
public static AuthenticationBuilder AddOidcAuthentication(this IServiceCollection services, IConfiguration configuration, string authenticationSectionName = "Authentication", IX509CertificateLoader? certificateLoader = null)
Parameters
servicesIServiceCollectionThe service collection.
configurationIConfigurationThe configuration.
authenticationSectionNamestringThe section bound to OidcAuthenticationSectionOptions. The default is
Authentication.certificateLoaderIX509CertificateLoaderThe loader of the certificates. When null, a default
X509CertificateLoaderis used.
Returns
- AuthenticationBuilder
The AuthenticationBuilder, to chain calls.
Examples
builder.Services.AddOidcAuthentication(builder.Configuration);
// ...
app.UseAuthentication();
app.UseAuthorization();
Remarks
Besides the authentication schemes, the method registers, from the sections named by OidcAuthenticationSectionOptions: the OpenID settings, the domain mappings, the token cache, the claims filler,
the on-behalf-of settings (Authentication:OnBehalfOf), the claim identifiers, the data protection keys (protected by the certificate of Authentication:DataProtection:EncryptionCertificate and stored in the cache described by
Authentication:DataProtection:CacheStore), the ticket store (Authentication:AuthenticationCacheTicketStore) and the bearer injector.
A minimal configuration:
{
"Application.configuration": { "ApplicationName": "MyApp" },
"Authentication": {
"DefaultAuthority": { "Url": "https://login.example.com/tenant/v2.0" },
"CookieName": ".MyApp.Cookies",
"OpenId.Settings": {
"ClientId": "my-client-id",
"ClientSecret": "my-client-secret",
"Audiences": [ "my-client-id" ],
"Scopes": [ "openid", "profile" ]
},
"DataProtection": {
"EncryptionCertificate": { "Store": { "Name": "MyAppCertificate" } },
"CacheStore": { "CacheKey": "DataProtection", "CacheName": "Default" }
},
"TokenCache": { "CacheName": "Default" }
}
}
Exceptions
- ConfigurationException
The section does not exist or a mandatory value (default authority, cookie name, claim types, section paths, response type, authentication method) is missing.
- MissingFieldException
A certificate cannot be found from its configuration section, or the OpenID settings have no client id, no scope, or no audience while
ValidateAudienceis true.
AddOidcAuthentication(IServiceCollection, Action<OidcAuthenticationOptions>)
Registers the OpenID Connect authentication with cookies, from code.
The default authenticate scheme is the Arc4uScheme policy scheme, which always forwards to OpenID Connect, and the user is signed in with a cookie.
The ticket store (see AuthenticationCacheTicketStoreOption), the data protection keys, the claim identifiers, the default authority and the OpenID settings are registered too.
public static AuthenticationBuilder AddOidcAuthentication(this IServiceCollection services, Action<OidcAuthenticationOptions> authenticationOptions)
Parameters
servicesIServiceCollectionThe service collection.
authenticationOptionsAction<OidcAuthenticationOptions>The action that configures the OidcAuthenticationOptions. OpenIdSettingsOptions, DataProtectionCertificate and DataProtectionCacheStoreOption are required.
Returns
- AuthenticationBuilder
The AuthenticationBuilder, to chain calls.
Examples
builder.Services.AddOidcAuthentication(options =>
{
options.DefaultAuthority = new AuthorityOptions(new Uri("https://login.example.com/tenant/v2.0"), null, null, null);
options.CookieName = ".MyApp.Cookies";
options.ApplicationName = "MyApp";
options.DataProtectionCertificate = certificate;
options.DataProtectionCacheStoreOption = o => { o.CacheKey = "DataProtection"; o.CacheName = "Default"; };
options.ClaimsIdentifierOptions = o => o.Add("oid");
options.OpenIdSettingsOptions = o =>
{
o.ClientId = "my-client-id";
o.ClientSecret = "my-client-secret";
o.Audiences.Add("my-client-id");
o.Scopes.Add("openid");
};
});
Exceptions
- ArgumentNullException
An argument, OpenIdSettingsOptions or DataProtectionCertificate is null.
- NullReferenceException
AddOidcClientAuthentication(IServiceCollection, IBrowser, ILoggerFactory, IConfiguration, string, string)
Registers the OpenID Connect authentication of a client application from the configuration. In addition to what the overload taking an action registers, the domain mappings, the claims filler and the extra authorization and token request parameters are read from the sections named by OidcClientAuthenticationSectionOptions.
public static void AddOidcClientAuthentication(this IServiceCollection services, IBrowser browser, ILoggerFactory loggerFactory, IConfiguration configuration, string authenticationSectionName = "Authentication", string settingsKey = "OidcClient")
Parameters
servicesIServiceCollectionThe service collection.
browserIBrowserThe browser that displays the login page.
loggerFactoryILoggerFactoryThe logger factory of the
OidcClient.configurationIConfigurationThe configuration.
authenticationSectionNamestringThe section bound to OidcClientAuthenticationSectionOptions. The default is
Authentication.settingsKeystringThe name of the key/value settings registered for the client. The default is
OidcClient.
Examples
services.AddOidcClientAuthentication(browser, loggerFactory, configuration);
Exceptions
- ConfigurationException
The section does not exist or a mandatory value is missing.
AddOidcClientAuthentication(IServiceCollection, IBrowser, ILoggerFactory, Action<OidcClientAuthenticationOptions>, string)
Registers the OpenID Connect authentication of a client application from code, based on Duende.IdentityModel.OidcClient: the OidcClient and its options
(authority, client id, scopes, redirect uris, browser), the default authority and the claim identifiers. The token provider named OidcClientIdentityModel uses them to log the user in.
public static void AddOidcClientAuthentication(this IServiceCollection services, IBrowser browser, ILoggerFactory loggerFactory, Action<OidcClientAuthenticationOptions> authenticationOptions, string settingsKey = "OidcClient")
Parameters
servicesIServiceCollectionThe service collection.
browserIBrowserThe browser that displays the login page.
loggerFactoryILoggerFactoryThe logger factory of the
OidcClient.authenticationOptionsAction<OidcClientAuthenticationOptions>The action that configures the OidcClientAuthenticationOptions. OidcClientSettingsOption is required.
settingsKeystringThe name of the key/value settings registered for the client. The default is
OidcClient.
Examples
services.AddOidcClientAuthentication(browser, loggerFactory, options =>
{
options.DefaultAuthority = new AuthorityOptions(new Uri("https://login.example.com/tenant/v2.0"), null, null, null);
options.CallbackPath = "myapp://callback";
options.PostLogoutRedirectUri = "myapp://callback";
options.ClaimsIdentifierOptions = o => o.Add("oid");
options.OidcClientSettingsOption = o =>
{
o.ClientId = "my-client-id";
o.Scopes.Add("openid");
o.Scopes.Add("offline_access");
};
});
Exceptions
- ArgumentNullException
An argument or a required option is null.