diff --git a/.editorconfig b/.editorconfig
index 38ed0fc0..351c4f27 100644
--- a/.editorconfig
+++ b/.editorconfig
@@ -7,9 +7,12 @@ root = true
[*]
charset = utf-8
indent_style = space
-indent_size = 2
+indent_size = 4
insert_final_newline = true
trim_trailing_whitespace = true
+dotnet_style_operator_placement_when_wrapping = beginning_of_line
+tab_width = 4
+end_of_line = crlf
[*.{cs,js,ts,sql,tql}]
@@ -21,15 +24,42 @@ csharp_space_between_method_call_parameter_list_parentheses = true
csharp_space_between_method_declaration_parameter_list_parentheses = true
csharp_space_after_keywords_in_control_flow_statements = false
csharp_space_between_parentheses = control_flow_statements
+csharp_space_around_binary_operators = before_and_after
# Motive: May be weird at first, but it improves readability.
csharp_style_prefer_primary_constructors = false:suggestion
# Primary constructors should be used only for very simple classes. May be record is a good choice.
+csharp_indent_labels = no_change
+# When using goto, labels should be explicitly positioned based on the algorithm.
+
+csharp_using_directive_placement = outside_namespace:silent
+# Rather standard placement of using in C#.
+
+csharp_indent_case_contents_when_block = false;
+# switch case block don't need another indent.
+
+csharp_prefer_braces = true:silent
+
+csharp_style_prefer_method_group_conversion = true:silent
+csharp_style_expression_bodied_methods = false:silent
+csharp_style_expression_bodied_constructors = false:silent
+csharp_style_expression_bodied_operators = false:silent
+csharp_style_expression_bodied_properties = true:silent
+csharp_style_expression_bodied_indexers = true:silent
+csharp_style_expression_bodied_accessors = true:silent
+csharp_style_expression_bodied_lambdas = true:silent
+
+csharp_style_prefer_top_level_statements = true:suggestion
+# Applies to Main().
+
+csharp_style_namespace_declarations=file_scoped:suggestion
+#Motive: Less useless space.
+
# internal and private fields should be _camelCase
dotnet_naming_rule.camel_case_for_private_internal_fields.severity = suggestion
dotnet_naming_rule.camel_case_for_private_internal_fields.symbols = private_internal_fields
-dotnet_naming_rule.camel_case_for_private_internal_fields.style = camel_case_underscore_style
+dotnet_naming_rule.camel_case_for_private_internal_fields.style = camel_case_underscore_style
dotnet_naming_symbols.private_internal_fields.applicable_kinds = field
dotnet_naming_symbols.private_internal_fields.applicable_accessibilities = private, internal
@@ -38,9 +68,6 @@ dotnet_naming_style.camel_case_underscore_style.required_prefix = _
dotnet_naming_style.camel_case_underscore_style.capitalization = camel_case
# Motive: It follow the C# style guideline.
-csharp_style_namespace_declarations=file_scoped:suggestion
-#Motive: Less useless space.
-
# CA1063: Implement IDisposable Correctly
dotnet_diagnostic.CA1063.severity = none
# CA1816: Dispose methods should call SuppressFinalize
@@ -118,6 +145,5 @@ dotnet_diagnostic.VSTHRD101.severity = error
# VSTHRD003: Avoid awaiting foreign Tasks
dotnet_diagnostic.VSTHRD003.severity = none
-
# /Signature-Code .editorconfig
diff --git a/CK.AspNet.Auth/AuthenticationCookieMode.cs b/CK.AspNet.Auth/AuthenticationCookieMode.cs
index 287b6428..039eadd2 100644
--- a/CK.AspNet.Auth/AuthenticationCookieMode.cs
+++ b/CK.AspNet.Auth/AuthenticationCookieMode.cs
@@ -3,33 +3,32 @@
using System.Collections.Generic;
using System.Text;
-namespace CK.AspNet.Auth
-{
+namespace CK.AspNet.Auth;
+
+///
+/// Describes the how the authentication cookie is managed.
+///
+public enum AuthenticationCookieMode
+{
///
- /// Describes the how the authentication cookie is managed.
+ /// The authentication cookie is set on the /c/.
+ /// This is the default mode.
///
- public enum AuthenticationCookieMode
- {
- ///
- /// The authentication cookie is set on the /c/.
- /// This is the default mode.
- ///
- WebFrontPath = 0,
+ WebFrontPath = 0,
- ///
- /// The authentication cookie is set on the root path:
- /// this enables the to act as a standard Cookie authentication
- /// service (applies to classical, server rendered, web site).
- ///
- RootPath = 1,
+ ///
+ /// The authentication cookie is set on the root path:
+ /// this enables the to act as a standard Cookie authentication
+ /// service (applies to classical, server rendered, web site).
+ ///
+ RootPath = 1,
- ///
- /// No authentication cookie is set (and no challenge is done).
- /// This also forces the to be false: this ensures that
- /// the long term cookie is also removed.
- ///
- None = 2
+ ///
+ /// No authentication cookie is set (and no challenge is done).
+ /// This also forces the to be false: this ensures that
+ /// the long term cookie is also removed.
+ ///
+ None = 2
- }
}
diff --git a/CK.AspNet.Auth/AuthenticationInfoTokenService.cs b/CK.AspNet.Auth/AuthenticationInfoTokenService.cs
index e23ebd5e..192926b8 100644
--- a/CK.AspNet.Auth/AuthenticationInfoTokenService.cs
+++ b/CK.AspNet.Auth/AuthenticationInfoTokenService.cs
@@ -4,114 +4,112 @@
using System;
using System.Diagnostics;
-namespace CK.AspNet.Auth
-{
- ///
- /// Simple singleton service that offers tokens creation and restoration functionalities.
- ///
- /// This is not specific to the global DI container, it is available from all containers.
- ///
- ///
- public sealed class AuthenticationInfoTokenService : ISingletonAutoService
- {
- readonly IAuthenticationTypeSystem _typeSystem;
- readonly IDataProtector _baseDataProtector;
- readonly IDataProtector _tokenDataProtector;
- readonly FrontAuthenticationInfoSecureDataFormat _frontTokenFormat;
+namespace CK.AspNet.Auth;
- public AuthenticationInfoTokenService( IAuthenticationTypeSystem typeSystem, IDataProtectionProvider dataProtectionProvider )
- {
- _typeSystem = typeSystem;
- Throw.DebugAssert( typeof( WebFrontAuthHandler ).FullName == "CK.AspNet.Auth.WebFrontAuthHandler" );
- _baseDataProtector = dataProtectionProvider.CreateProtector( "CK.AspNet.Auth.WebFrontAuthHandler" );
- _tokenDataProtector = _baseDataProtector.CreateProtector( "Token", "v1" );
- _frontTokenFormat = new FrontAuthenticationInfoSecureDataFormat( _typeSystem, _tokenDataProtector );
- }
+///
+/// Simple singleton service that offers tokens creation and restoration functionalities.
+///
+/// This is not specific to the global DI container, it is available from all containers.
+///
+///
+public sealed class AuthenticationInfoTokenService : ISingletonAutoService
+{
+ readonly IAuthenticationTypeSystem _typeSystem;
+ readonly IDataProtector _baseDataProtector;
+ readonly IDataProtector _tokenDataProtector;
+ readonly FrontAuthenticationInfoSecureDataFormat _frontTokenFormat;
- ///
- /// Gets the type system service.
- ///
- public IAuthenticationTypeSystem TypeSystem => _typeSystem;
+ public AuthenticationInfoTokenService( IAuthenticationTypeSystem typeSystem, IDataProtectionProvider dataProtectionProvider )
+ {
+ _typeSystem = typeSystem;
+ Throw.DebugAssert( typeof( WebFrontAuthHandler ).FullName == "CK.AspNet.Auth.WebFrontAuthHandler" );
+ _baseDataProtector = dataProtectionProvider.CreateProtector( "CK.AspNet.Auth.WebFrontAuthHandler" );
+ _tokenDataProtector = _baseDataProtector.CreateProtector( "Token", "v1" );
+ _frontTokenFormat = new FrontAuthenticationInfoSecureDataFormat( _typeSystem, _tokenDataProtector );
+ }
- ///
- /// Gets the data protector to use for authentication tokens.
- ///
- public IDataProtector TokenDataProtector => _tokenDataProtector;
+ ///
+ /// Gets the type system service.
+ ///
+ public IAuthenticationTypeSystem TypeSystem => _typeSystem;
- ///
- /// Base data protector for authentication related protected data.
- ///
- public IDataProtector BaseDataProtector => _baseDataProtector;
+ ///
+ /// Gets the data protector to use for authentication tokens.
+ ///
+ public IDataProtector TokenDataProtector => _tokenDataProtector;
- ///
- /// Creates a token from a .
- ///
- /// The authentication info.
- /// The url-safe secured authentication token string.
- public string ProtectFrontAuthenticationInfo( FrontAuthenticationInfo info )
- {
- Debug.Assert( info.Info != null );
- return _frontTokenFormat.Protect( info );
- }
+ ///
+ /// Base data protector for authentication related protected data.
+ ///
+ public IDataProtector BaseDataProtector => _baseDataProtector;
- ///
- /// Extracts a from a token previously created with .
- ///
- /// By default, the expiration is checked based on .
- /// If expiration check must be skipped, use as the expiration date.
- ///
- ///
- /// The token.
- /// Optional check expiration date. Defaults to .
- /// The information (possibly expired) or null if an error occurred.
- public FrontAuthenticationInfo? UnprotectFrontAuthenticationInfo( string data, DateTime? checkExpirationDate = null )
- {
- Throw.CheckNotNullArgument( data );
- var info = _frontTokenFormat.Unprotect( data )!;
- if( info == null ) return null;
- return info.SetInfo( info.Info.CheckExpiration( checkExpirationDate ?? DateTime.UtcNow ) );
- }
+ ///
+ /// Creates a token from a .
+ ///
+ /// The authentication info.
+ /// The url-safe secured authentication token string.
+ public string ProtectFrontAuthenticationInfo( FrontAuthenticationInfo info )
+ {
+ Debug.Assert( info.Info != null );
+ return _frontTokenFormat.Protect( info );
+ }
- ///
- /// Direct generation of an authentication token from any .
- /// is called with .
- ///
- /// By default, the expiration is checked based on .
- /// If expiration check must be skipped, use as the expiration date.
- ///
- ///
- /// This is to be used with caution: the authentication token should never be sent to any client and should be
- /// used only for secure server to server temporary authentication.
- ///
- ///
- /// The authentication info for which an authentication token must be obtained.
- /// Optional check expiration date. Defaults to .
- /// The url-safe secured authentication token string.
- public string UnsafeCreateAuthenticationToken( IAuthenticationInfo info, DateTime? checkExpirationDate = null )
- {
- Throw.CheckNotNullArgument( info );
- info = info.CheckExpiration( checkExpirationDate ?? DateTime.UtcNow );
- return ProtectFrontAuthenticationInfo( new FrontAuthenticationInfo( info, false ) );
- }
+ ///
+ /// Extracts a from a token previously created with .
+ ///
+ /// By default, the expiration is checked based on .
+ /// If expiration check must be skipped, use as the expiration date.
+ ///
+ ///
+ /// The token.
+ /// Optional check expiration date. Defaults to .
+ /// The information (possibly expired) or null if an error occurred.
+ public FrontAuthenticationInfo? UnprotectFrontAuthenticationInfo( string data, DateTime? checkExpirationDate = null )
+ {
+ Throw.CheckNotNullArgument( data );
+ var info = _frontTokenFormat.Unprotect( data )!;
+ if( info == null ) return null;
+ return info.SetInfo( info.Info.CheckExpiration( checkExpirationDate ?? DateTime.UtcNow ) );
+ }
- ///
- /// Direct generation of an authentication token for a user.
- ///
- /// This is to be used with caution: the authentication token should never be sent to any client and should be
- /// used only for secure server to server temporary authentication.
- ///
- ///
- /// The user identifier.
- /// The user name.
- /// The validity time span: the shorter the better.
- /// The url-safe secured authentication token string.
- public string UnsafeCreateAuthenticationToken( int userId, string userName, TimeSpan validity )
- {
- var u = _typeSystem.UserInfo.Create( userId, userName );
- var info = _typeSystem.AuthenticationInfo.Create( u, DateTime.UtcNow.Add( validity ) );
- return ProtectFrontAuthenticationInfo( new FrontAuthenticationInfo( info, false ) );
- }
+ ///
+ /// Direct generation of an authentication token from any .
+ /// is called with .
+ ///
+ /// By default, the expiration is checked based on .
+ /// If expiration check must be skipped, use as the expiration date.
+ ///
+ ///
+ /// This is to be used with caution: the authentication token should never be sent to any client and should be
+ /// used only for secure server to server temporary authentication.
+ ///
+ ///
+ /// The authentication info for which an authentication token must be obtained.
+ /// Optional check expiration date. Defaults to .
+ /// The url-safe secured authentication token string.
+ public string UnsafeCreateAuthenticationToken( IAuthenticationInfo info, DateTime? checkExpirationDate = null )
+ {
+ Throw.CheckNotNullArgument( info );
+ info = info.CheckExpiration( checkExpirationDate ?? DateTime.UtcNow );
+ return ProtectFrontAuthenticationInfo( new FrontAuthenticationInfo( info, false ) );
+ }
+ ///
+ /// Direct generation of an authentication token for a user.
+ ///
+ /// This is to be used with caution: the authentication token should never be sent to any client and should be
+ /// used only for secure server to server temporary authentication.
+ ///
+ ///
+ /// The user identifier.
+ /// The user name.
+ /// The validity time span: the shorter the better.
+ /// The url-safe secured authentication token string.
+ public string UnsafeCreateAuthenticationToken( int userId, string userName, TimeSpan validity )
+ {
+ var u = _typeSystem.UserInfo.Create( userId, userName );
+ var info = _typeSystem.AuthenticationInfo.Create( u, DateTime.UtcNow.Add( validity ) );
+ return ProtectFrontAuthenticationInfo( new FrontAuthenticationInfo( info, false ) );
}
}
diff --git a/CK.AspNet.Auth/CKAspNetAuthHttpContextExtensions.cs b/CK.AspNet.Auth/CKAspNetAuthHttpContextExtensions.cs
index f3a5a674..a435cd05 100644
--- a/CK.AspNet.Auth/CKAspNetAuthHttpContextExtensions.cs
+++ b/CK.AspNet.Auth/CKAspNetAuthHttpContextExtensions.cs
@@ -6,34 +6,33 @@
using System.Collections.Generic;
using System.Text;
-namespace Microsoft.AspNetCore.Http
+namespace Microsoft.AspNetCore.Http;
+
+///
+/// Exposes extension method on .
+///
+static public class CKAspNetAuthHttpContextExtensions
{
///
- /// Exposes extension method on .
+ /// Obtains the current , either because it is already
+ /// in or by extracting authentication from request.
+ /// It is never null, but can be .
///
- static public class CKAspNetAuthHttpContextExtensions
+ /// This context.
+ /// Never null, can be .
+ static public IAuthenticationInfo GetAuthenticationInfo( this HttpContext @this )
{
- ///
- /// Obtains the current , either because it is already
- /// in or by extracting authentication from request.
- /// It is never null, but can be .
- ///
- /// This context.
- /// Never null, can be .
- static public IAuthenticationInfo GetAuthenticationInfo( this HttpContext @this )
+ IAuthenticationInfo? authInfo;
+ if( @this.Items.TryGetValue( typeof( FrontAuthenticationInfo ), out var o ) && o != null )
+ {
+ authInfo = ((FrontAuthenticationInfo)o).Info;
+ }
+ else
{
- IAuthenticationInfo? authInfo;
- if( @this.Items.TryGetValue( typeof( FrontAuthenticationInfo ), out var o ) && o != null )
- {
- authInfo = ((FrontAuthenticationInfo)o).Info;
- }
- else
- {
- IActivityMonitor? monitor = null;
- var s = @this.RequestServices.GetRequiredService();
- authInfo = s.ReadAndCacheAuthenticationHeader( @this, ref monitor ).Info;
- }
- return authInfo;
+ IActivityMonitor? monitor = null;
+ var s = @this.RequestServices.GetRequiredService();
+ authInfo = s.ReadAndCacheAuthenticationHeader( @this, ref monitor ).Info;
}
+ return authInfo;
}
}
diff --git a/CK.AspNet.Auth/Extensions/AutoBindingAccount/IWebFrontAuthAutoBindingAccountContext.cs b/CK.AspNet.Auth/Extensions/AutoBindingAccount/IWebFrontAuthAutoBindingAccountContext.cs
index 019cba56..99e3d051 100644
--- a/CK.AspNet.Auth/Extensions/AutoBindingAccount/IWebFrontAuthAutoBindingAccountContext.cs
+++ b/CK.AspNet.Auth/Extensions/AutoBindingAccount/IWebFrontAuthAutoBindingAccountContext.cs
@@ -5,86 +5,85 @@
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Primitives;
-namespace CK.AspNet.Auth
+namespace CK.AspNet.Auth;
+
+///
+/// Enables to
+/// attempt to bind an account to a currently already logged in user.
+///
+public interface IWebFrontAuthAutoBindingAccountContext
{
///
- /// Enables to
- /// attempt to bind an account to a currently already logged in user.
+ /// Gets the current http context.
///
- public interface IWebFrontAuthAutoBindingAccountContext
- {
- ///
- /// Gets the current http context.
- ///
- HttpContext HttpContext { get; }
+ HttpContext HttpContext { get; }
- ///
- /// Gets the authentication type system.
- ///
- IAuthenticationTypeSystem AuthenticationTypeSystem { get; }
+ ///
+ /// Gets the authentication type system.
+ ///
+ IAuthenticationTypeSystem AuthenticationTypeSystem { get; }
- ///
- /// Gets the endpoint that started the authentication.
- ///
- WebFrontAuthLoginMode LoginMode { get; }
+ ///
+ /// Gets the endpoint that started the authentication.
+ ///
+ WebFrontAuthLoginMode LoginMode { get; }
- ///
- /// Gets the return url only if '/c/startLogin' has been called with a 'returnUrl' parameter.
- /// Null otherwise.
- ///
- /// This url is always checked against the set of allowed prefixes.
- ///
- ///
- string? ReturnUrl { get; }
+ ///
+ /// Gets the return url only if '/c/startLogin' has been called with a 'returnUrl' parameter.
+ /// Null otherwise.
+ ///
+ /// This url is always checked against the set of allowed prefixes.
+ ///
+ ///
+ string? ReturnUrl { get; }
- ///
- /// Gets the authentication provider on which .webfront/c/starLogin has been called.
- /// This is "Basic" when is
- /// and null when LoginMode is .
- ///
- string? InitialScheme { get; }
+ ///
+ /// Gets the authentication provider on which .webfront/c/starLogin has been called.
+ /// This is "Basic" when is
+ /// and null when LoginMode is .
+ ///
+ string? InitialScheme { get; }
- ///
- /// Gets the calling authentication scheme.
- /// This is usually the same as the .
- ///
- string CallingScheme { get; }
+ ///
+ /// Gets the calling authentication scheme.
+ /// This is usually the same as the .
+ ///
+ string CallingScheme { get; }
- ///
- /// Gets the provider payload (type is provider -ie. - dependent).
- /// This is never null but may be an empty object when unsafe login is used with no payload.
- ///
- object Payload { get; }
+ ///
+ /// Gets the provider payload (type is provider -ie. - dependent).
+ /// This is never null but may be an empty object when unsafe login is used with no payload.
+ ///
+ object Payload { get; }
- ///
- /// Gets the query parameters (for GET) or form data (when POST was used) of the
- /// initial .webfront/c/starLogin call as a readonly list.
- ///
- IDictionary UserData { get; }
+ ///
+ /// Gets the query parameters (for GET) or form data (when POST was used) of the
+ /// initial .webfront/c/starLogin call as a readonly list.
+ ///
+ IDictionary UserData { get; }
- ///
- /// Gets the authentication information of the current authentication.
- ///
- IAuthenticationInfo InitialAuthentication { get; }
+ ///
+ /// Gets the authentication information of the current authentication.
+ ///
+ IAuthenticationInfo InitialAuthentication { get; }
- ///
- /// Sets an error and always returns null to easily return
- /// from method.
- ///
- /// Error identifier (a dotted identifier string). Must not be null or empty.
- /// The optional error message in clear text (typically in English).
- /// Always null.
- UserLoginResult? SetError( string errorId, string? errorText = null );
+ ///
+ /// Sets an error and always returns null to easily return
+ /// from method.
+ ///
+ /// Error identifier (a dotted identifier string). Must not be null or empty.
+ /// The optional error message in clear text (typically in English).
+ /// Always null.
+ UserLoginResult? SetError( string errorId, string? errorText = null );
- ///
- /// Sets an error and always returns null to easily return
- /// from method.
- /// The returned error has "errorId" set to the full name of the exception
- /// and the "errorText" is the .
- /// Can be called multiple times: new error information replaces the previous one.
- ///
- /// The exception. Can not be null.
- /// Always null.
- UserLoginResult? SetError( Exception ex );
- }
+ ///
+ /// Sets an error and always returns null to easily return
+ /// from method.
+ /// The returned error has "errorId" set to the full name of the exception
+ /// and the "errorText" is the .
+ /// Can be called multiple times: new error information replaces the previous one.
+ ///
+ /// The exception. Can not be null.
+ /// Always null.
+ UserLoginResult? SetError( Exception ex );
}
diff --git a/CK.AspNet.Auth/Extensions/AutoBindingAccount/IWebFrontAuthAutoBindingAccountService.cs b/CK.AspNet.Auth/Extensions/AutoBindingAccount/IWebFrontAuthAutoBindingAccountService.cs
index f2e80685..865ba416 100644
--- a/CK.AspNet.Auth/Extensions/AutoBindingAccount/IWebFrontAuthAutoBindingAccountService.cs
+++ b/CK.AspNet.Auth/Extensions/AutoBindingAccount/IWebFrontAuthAutoBindingAccountService.cs
@@ -5,31 +5,30 @@
using CK.Auth;
using CK.Core;
-namespace CK.AspNet.Auth
+namespace CK.AspNet.Auth;
+
+///
+/// Optional service that, when registered, enables automatic account binding.
+/// Implementation may consider that when current authentication is it is safe
+/// to bind the account.
+///
+[ContainerConfiguredSingletonService]
+public interface IWebFrontAuthAutoBindingAccountService : ISingletonAutoService
{
///
- /// Optional service that, when registered, enables automatic account binding.
- /// Implementation may consider that when current authentication is it is safe
- /// to bind the account.
+ /// Called for each failed login when the user is currently logged in.
///
- [ContainerConfiguredSingletonService]
- public interface IWebFrontAuthAutoBindingAccountService : ISingletonAutoService
- {
- ///
- /// Called for each failed login when the user is currently logged in.
- ///
- /// The monitor to use.
- /// Account binding context.
- ///
- /// The login result where the may have its
- /// updated with the new one (the current logged in user available on
- /// may be returned but this is quite useless).
- ///
- /// Null to return the standard User.NoAutoBinding/"Automatic account binding is disabled." error
- /// or the error identifier and error text have been set via
- /// or .
- ///
- ///
- Task BindAccountAsync( IActivityMonitor monitor, IWebFrontAuthAutoBindingAccountContext context );
- }
+ /// The monitor to use.
+ /// Account binding context.
+ ///
+ /// The login result where the may have its
+ /// updated with the new one (the current logged in user available on
+ /// may be returned but this is quite useless).
+ ///
+ /// Null to return the standard User.NoAutoBinding/"Automatic account binding is disabled." error
+ /// or the error identifier and error text have been set via
+ /// or .
+ ///
+ ///
+ Task BindAccountAsync( IActivityMonitor monitor, IWebFrontAuthAutoBindingAccountContext context );
}
diff --git a/CK.AspNet.Auth/Extensions/AutoCreateAccount/IWebFrontAuthAutoCreateAccountContext.cs b/CK.AspNet.Auth/Extensions/AutoCreateAccount/IWebFrontAuthAutoCreateAccountContext.cs
index 9abe7e83..22f13919 100644
--- a/CK.AspNet.Auth/Extensions/AutoCreateAccount/IWebFrontAuthAutoCreateAccountContext.cs
+++ b/CK.AspNet.Auth/Extensions/AutoCreateAccount/IWebFrontAuthAutoCreateAccountContext.cs
@@ -5,79 +5,78 @@
using System.Collections.Generic;
using System.Text;
-namespace CK.AspNet.Auth
+namespace CK.AspNet.Auth;
+
+///
+/// Enables to
+/// attempt to create an account and log in the user based on any criteria exposed by this context.
+///
+public interface IWebFrontAuthAutoCreateAccountContext
{
///
- /// Enables to
- /// attempt to create an account and log in the user based on any criteria exposed by this context.
+ /// Gets the current http context.
///
- public interface IWebFrontAuthAutoCreateAccountContext
- {
- ///
- /// Gets the current http context.
- ///
- HttpContext HttpContext { get; }
+ HttpContext HttpContext { get; }
- ///
- /// Gets the authentication type system.
- ///
- IAuthenticationTypeSystem AuthenticationTypeSystem { get; }
+ ///
+ /// Gets the authentication type system.
+ ///
+ IAuthenticationTypeSystem AuthenticationTypeSystem { get; }
- ///
- /// Gets the endpoint that started the authentication.
- ///
- WebFrontAuthLoginMode LoginMode { get; }
+ ///
+ /// Gets the endpoint that started the authentication.
+ ///
+ WebFrontAuthLoginMode LoginMode { get; }
- ///
- /// Gets the return url only if '/c/startLogin' has been called with a 'returnUrl' parameter.
- /// Null otherwise.
- ///
- string? ReturnUrl { get; }
+ ///
+ /// Gets the return url only if '/c/startLogin' has been called with a 'returnUrl' parameter.
+ /// Null otherwise.
+ ///
+ string? ReturnUrl { get; }
- ///
- /// Gets the authentication provider on which .webfront/c/starLogin has been called.
- /// This is "Basic" when is
- /// and null when LoginMode is .
- ///
- string? InitialScheme { get; }
+ ///
+ /// Gets the authentication provider on which .webfront/c/starLogin has been called.
+ /// This is "Basic" when is
+ /// and null when LoginMode is .
+ ///
+ string? InitialScheme { get; }
- ///
- /// Gets the calling authentication scheme.
- /// This is usually the same as the .
- ///
- string CallingScheme { get; }
+ ///
+ /// Gets the calling authentication scheme.
+ /// This is usually the same as the .
+ ///
+ string CallingScheme { get; }
- ///
- /// Gets the provider payload (type is provider -ie. - dependent).
- /// This is never null but may be an empty object when unsafe login is used with no payload.
- ///
- object Payload { get; }
+ ///
+ /// Gets the provider payload (type is provider -ie. - dependent).
+ /// This is never null but may be an empty object when unsafe login is used with no payload.
+ ///
+ object Payload { get; }
- ///
- /// Gets the query parameters (for GET) or form data (when POST was used) of the
- /// initial .webfront/c/starLogin call as a readonly list.
- ///
- IDictionary UserData { get; }
+ ///
+ /// Gets the query parameters (for GET) or form data (when POST was used) of the
+ /// initial .webfront/c/starLogin call as a readonly list.
+ ///
+ IDictionary UserData { get; }
- ///
- /// Sets an error and always returns null to easily return
- /// from method.
- ///
- /// Error identifier (a dotted identifier string). Must not be null or empty.
- /// The optional error message in clear text (typically in english).
- /// Always null.
- UserLoginResult? SetError( string errorId, string? errorText = null );
+ ///
+ /// Sets an error and always returns null to easily return
+ /// from method.
+ ///
+ /// Error identifier (a dotted identifier string). Must not be null or empty.
+ /// The optional error message in clear text (typically in english).
+ /// Always null.
+ UserLoginResult? SetError( string errorId, string? errorText = null );
- ///
- /// Sets an error and always returns null to easily return
- /// from method.
- /// The returned error has "errorId" set to the full name of the exception
- /// and the "errorText" is the .
- /// Can be called multiple times: new error information replaces the previous one.
- ///
- /// The exception. Can not be null.
- /// Always null.
- UserLoginResult? SetError( Exception ex );
+ ///
+ /// Sets an error and always returns null to easily return
+ /// from method.
+ /// The returned error has "errorId" set to the full name of the exception
+ /// and the "errorText" is the .
+ /// Can be called multiple times: new error information replaces the previous one.
+ ///
+ /// The exception. Can not be null.
+ /// Always null.
+ UserLoginResult? SetError( Exception ex );
- }
}
diff --git a/CK.AspNet.Auth/Extensions/AutoCreateAccount/IWebFrontAuthAutoCreateAccountService.cs b/CK.AspNet.Auth/Extensions/AutoCreateAccount/IWebFrontAuthAutoCreateAccountService.cs
index 1bd152ea..c6e9a7c9 100644
--- a/CK.AspNet.Auth/Extensions/AutoCreateAccount/IWebFrontAuthAutoCreateAccountService.cs
+++ b/CK.AspNet.Auth/Extensions/AutoCreateAccount/IWebFrontAuthAutoCreateAccountService.cs
@@ -7,31 +7,30 @@
using System.Text;
using System.Threading.Tasks;
-namespace CK.AspNet.Auth
+namespace CK.AspNet.Auth;
+
+///
+/// Optional service that, when registered, enables automatic account creation.
+/// This should be used with care.
+/// The should typically
+/// contain a special key (like an "InvitationToken") with a relatively short life timed and verifiable value that should be
+/// required to actually create the account and log in the user.
+/// Also, not all schemes should be systematically supported, nor all .
+///
+[ContainerConfiguredSingletonService]
+public interface IWebFrontAuthAutoCreateAccountService : ISingletonAutoService
{
///
- /// Optional service that, when registered, enables automatic account creation.
- /// This should be used with care.
- /// The should typically
- /// contain a special key (like an "InvitationToken") with a relatively short life timed and verifiable value that should be
- /// required to actually create the account and log in the user.
- /// Also, not all schemes should be systematically supported, nor all .
+ /// Called for each failed login when is true and when there is
+ /// no current authentication.
///
- [ContainerConfiguredSingletonService]
- public interface IWebFrontAuthAutoCreateAccountService : ISingletonAutoService
- {
- ///
- /// Called for each failed login when is true and when there is
- /// no current authentication.
- ///
- /// The monitor to use.
- /// Account creation context.
- ///
- /// The login result that may be automatically created AND logged in.
- /// Null to return the standard User.NoAutoRegistration/"Automatic user registration is disabled." error
- /// or the error identifier and error text have been set via
- /// or .
- ///
- Task CreateAccountAndLoginAsync( IActivityMonitor monitor, IWebFrontAuthAutoCreateAccountContext context );
- }
+ /// The monitor to use.
+ /// Account creation context.
+ ///
+ /// The login result that may be automatically created AND logged in.
+ /// Null to return the standard User.NoAutoRegistration/"Automatic user registration is disabled." error
+ /// or the error identifier and error text have been set via
+ /// or .
+ ///
+ Task CreateAccountAndLoginAsync( IActivityMonitor monitor, IWebFrontAuthAutoCreateAccountContext context );
}
diff --git a/CK.AspNet.Auth/Extensions/IWebFrontAuthDynamicScopeProvider.cs b/CK.AspNet.Auth/Extensions/IWebFrontAuthDynamicScopeProvider.cs
index b56f307a..5cc1e07e 100644
--- a/CK.AspNet.Auth/Extensions/IWebFrontAuthDynamicScopeProvider.cs
+++ b/CK.AspNet.Auth/Extensions/IWebFrontAuthDynamicScopeProvider.cs
@@ -2,30 +2,29 @@
using Microsoft.AspNetCore.Authentication;
using System.Threading.Tasks;
-namespace CK.AspNet.Auth
+namespace CK.AspNet.Auth;
+
+///
+/// Optional service that can handle dynamic scopes.
+/// This service provides the scopes that must be submitted to an authentication provider.
+///
+/// Updating the actual scopes that have been accepted or rejected is a specific process
+/// that must be implemented for each provider.
+///
+///
+/// For instance: Facebook requires to use its GraphQL API to know which scopes have been
+/// accepted or rejected by the user.
+/// Others simply returns these informations in the .
+///
+///
+[ContainerConfiguredSingletonService]
+public interface IWebFrontAuthDynamicScopeProvider : ISingletonAutoService
{
///
- /// Optional service that can handle dynamic scopes.
- /// This service provides the scopes that must be submitted to an authentication provider.
- ///
- /// Updating the actual scopes that have been accepted or rejected is a specific process
- /// that must be implemented for each provider.
- ///
- ///
- /// For instance: Facebook requires to use its GraphQL API to know which scopes have been
- /// accepted or rejected by the user.
- /// Others simply returns these informations in the .
- ///
+ /// Called at the start of the external login flow.
///
- [ContainerConfiguredSingletonService]
- public interface IWebFrontAuthDynamicScopeProvider : ISingletonAutoService
- {
- ///
- /// Called at the start of the external login flow.
- ///
- /// The monitor to use.
- /// The context.
- /// Scopes that should be submitted.
- Task GetScopesAsync( IActivityMonitor m, WebFrontAuthStartLoginContext context );
- }
+ /// The monitor to use.
+ /// The context.
+ /// Scopes that should be submitted.
+ Task GetScopesAsync( IActivityMonitor m, WebFrontAuthStartLoginContext context );
}
diff --git a/CK.AspNet.Auth/Extensions/IWebFrontAuthImpersonationService.cs b/CK.AspNet.Auth/Extensions/IWebFrontAuthImpersonationService.cs
index f125c517..ae7bf994 100644
--- a/CK.AspNet.Auth/Extensions/IWebFrontAuthImpersonationService.cs
+++ b/CK.AspNet.Auth/Extensions/IWebFrontAuthImpersonationService.cs
@@ -6,41 +6,40 @@
using System.Text;
using System.Threading.Tasks;
-namespace CK.AspNet.Auth
+namespace CK.AspNet.Auth;
+
+///
+/// Optional service that controls user impersonation either by user identifier or user name.
+/// Impersonation is not an actual login, it must have no visible impact on the impersonated user data.
+///
+[ContainerConfiguredSingletonService]
+public interface IWebFrontAuthImpersonationService : ISingletonAutoService
{
///
- /// Optional service that controls user impersonation either by user identifier or user name.
- /// Impersonation is not an actual login, it must have no visible impact on the impersonated user data.
+ /// Attempts to impersonate the current user into another one.
+ /// Should return the user information on success and null if impersonation is not allowed.
///
- [ContainerConfiguredSingletonService]
- public interface IWebFrontAuthImpersonationService : ISingletonAutoService
- {
- ///
- /// Attempts to impersonate the current user into another one.
- /// Should return the user information on success and null if impersonation is not allowed.
- ///
- /// The HttpContext.
- /// The monitor to use.
- /// The current user information.
- /// The target user identifier.
- /// The target impersonated user or null if impersonation is not possible.
- Task ImpersonateAsync( HttpContext ctx,
- IActivityMonitor monitor,
- IAuthenticationInfo info,
- int userId );
+ /// The HttpContext.
+ /// The monitor to use.
+ /// The current user information.
+ /// The target user identifier.
+ /// The target impersonated user or null if impersonation is not possible.
+ Task ImpersonateAsync( HttpContext ctx,
+ IActivityMonitor monitor,
+ IAuthenticationInfo info,
+ int userId );
- ///
- /// Attempts to impersonate the current user into another one.
- /// Should return the user information on success and null if impersonation is not allowed.
- ///
- /// The HttpContext.
- /// The monitor to use.
- /// The current user information.
- /// The target user name.
- /// The target impersonated user or null if impersonation is not possible.
- Task ImpersonateAsync( HttpContext ctx,
- IActivityMonitor monitor,
- IAuthenticationInfo info,
- string userName );
- }
+ ///
+ /// Attempts to impersonate the current user into another one.
+ /// Should return the user information on success and null if impersonation is not allowed.
+ ///
+ /// The HttpContext.
+ /// The monitor to use.
+ /// The current user information.
+ /// The target user name.
+ /// The target impersonated user or null if impersonation is not possible.
+ Task ImpersonateAsync( HttpContext ctx,
+ IActivityMonitor monitor,
+ IAuthenticationInfo info,
+ string userName );
}
diff --git a/CK.AspNet.Auth/Extensions/IWebFrontAuthUnsafeDirectLoginAllowService.cs b/CK.AspNet.Auth/Extensions/IWebFrontAuthUnsafeDirectLoginAllowService.cs
index 22826673..f4fa09fd 100644
--- a/CK.AspNet.Auth/Extensions/IWebFrontAuthUnsafeDirectLoginAllowService.cs
+++ b/CK.AspNet.Auth/Extensions/IWebFrontAuthUnsafeDirectLoginAllowService.cs
@@ -2,25 +2,24 @@
using Microsoft.AspNetCore.Http;
using System.Threading.Tasks;
-namespace CK.AspNet.Auth
+namespace CK.AspNet.Auth;
+
+///
+/// Optional service that can allow calls to the dangerous '/c/unsafeDirectLogin'.
+/// Enabling calls to to this endpoint must be explicit: by default "403 - Forbidden"
+/// is always returned.
+///
+[ContainerConfiguredSingletonService]
+public interface IWebFrontAuthUnsafeDirectLoginAllowService : ISingletonAutoService
{
///
- /// Optional service that can allow calls to the dangerous '/c/unsafeDirectLogin'.
- /// Enabling calls to to this endpoint must be explicit: by default "403 - Forbidden"
- /// is always returned.
+ /// Predicate function that may allow calls to '/c/unsafeDirectLogin' for a
+ /// scheme and a payload.
///
- [ContainerConfiguredSingletonService]
- public interface IWebFrontAuthUnsafeDirectLoginAllowService : ISingletonAutoService
- {
- ///
- /// Predicate function that may allow calls to '/c/unsafeDirectLogin' for a
- /// scheme and a payload.
- ///
- /// The current context.
- /// The monitor to use.
- /// The authentication scheme.
- /// The login payload for the scheme.
- /// True if the call must be allowed, false otherwise.
- Task AllowAsync( HttpContext ctx, IActivityMonitor monitor, string scheme, object payload );
- }
+ /// The current context.
+ /// The monitor to use.
+ /// The authentication scheme.
+ /// The login payload for the scheme.
+ /// True if the call must be allowed, false otherwise.
+ Task AllowAsync( HttpContext ctx, IActivityMonitor monitor, string scheme, object payload );
}
diff --git a/CK.AspNet.Auth/Extensions/ValidateLogin/IWebFrontAuthValidateLoginContext.cs b/CK.AspNet.Auth/Extensions/ValidateLogin/IWebFrontAuthValidateLoginContext.cs
index 8baa13f9..d4b8eb45 100644
--- a/CK.AspNet.Auth/Extensions/ValidateLogin/IWebFrontAuthValidateLoginContext.cs
+++ b/CK.AspNet.Auth/Extensions/ValidateLogin/IWebFrontAuthValidateLoginContext.cs
@@ -5,83 +5,82 @@
using System.Collections.Generic;
using System.Text;
-namespace CK.AspNet.Auth
+namespace CK.AspNet.Auth;
+
+///
+/// Enables to
+/// cancel login based on any criteria exposed by this context.
+///
+public interface IWebFrontAuthValidateLoginContext
{
///
- /// Enables to
- /// cancel login based on any criteria exposed by this context.
+ /// Gets the current http context.
///
- public interface IWebFrontAuthValidateLoginContext
- {
- ///
- /// Gets the current http context.
- ///
- HttpContext HttpContext { get; }
+ HttpContext HttpContext { get; }
- ///
- /// Gets the authentication type system.
- ///
- IAuthenticationTypeSystem AuthenticationTypeSystem { get; }
+ ///
+ /// Gets the authentication type system.
+ ///
+ IAuthenticationTypeSystem AuthenticationTypeSystem { get; }
- ///
- /// Gets the endpoint that started the authentication.
- ///
- WebFrontAuthLoginMode LoginMode { get; }
+ ///
+ /// Gets the endpoint that started the authentication.
+ ///
+ WebFrontAuthLoginMode LoginMode { get; }
- ///
- /// Gets the return url only if '/c/startLogin' has been called with a 'returnUrl' parameter.
- /// Null otherwise.
- ///
- string? ReturnUrl { get; }
+ ///
+ /// Gets the return url only if '/c/startLogin' has been called with a 'returnUrl' parameter.
+ /// Null otherwise.
+ ///
+ string? ReturnUrl { get; }
- ///
- /// Gets the authentication provider on which .webfront/c/starLogin has been called.
- /// This is "Basic" when is
- /// and null when LoginMode is .
- ///
- string? InitialScheme { get; }
+ ///
+ /// Gets the authentication provider on which .webfront/c/starLogin has been called.
+ /// This is "Basic" when is
+ /// and null when LoginMode is .
+ ///
+ string? InitialScheme { get; }
- ///
- /// Gets the calling authentication scheme.
- /// This is usually the same as the .
- ///
- string CallingScheme { get; }
+ ///
+ /// Gets the calling authentication scheme.
+ /// This is usually the same as the .
+ ///
+ string CallingScheme { get; }
- ///
- /// Gets the current authentication when .webfront/c/starLogin has been called
- /// or the current authentication when is
- /// or .
- ///
- IAuthenticationInfo InitialAuthentication { get; }
+ ///
+ /// Gets the current authentication when .webfront/c/starLogin has been called
+ /// or the current authentication when is
+ /// or .
+ ///
+ IAuthenticationInfo InitialAuthentication { get; }
- ///
- /// Gets the query parameters (for GET) or form data (when POST was used) of the
- /// initial .webfront/c/starLogin call as a readonly list.
- ///
- IDictionary UserData { get; }
+ ///
+ /// Gets the query parameters (for GET) or form data (when POST was used) of the
+ /// initial .webfront/c/starLogin call as a readonly list.
+ ///
+ IDictionary UserData { get; }
- ///
- /// Gets whether an error has already been set.
- ///
- bool HasError { get; }
+ ///
+ /// Gets whether an error has already been set.
+ ///
+ bool HasError { get; }
- ///
- /// Cancels the login and sets an error message.
- /// The returned error contains the , the ,
- /// , and optionally the .
- /// Can be called multiple times: new error information replaces the previous one.
- ///
- /// Error identifier (a dotted identifier string). Can not be null or empty.
- /// The error message in clear text.
- void SetError( string errorId, string errorText );
+ ///
+ /// Cancels the login and sets an error message.
+ /// The returned error contains the , the ,
+ /// , and optionally the .
+ /// Can be called multiple times: new error information replaces the previous one.
+ ///
+ /// Error identifier (a dotted identifier string). Can not be null or empty.
+ /// The error message in clear text.
+ void SetError( string errorId, string errorText );
- ///
- /// Cancels the login and sets an error message.
- /// The returned error has "errorId" set to the full name of the exception
- /// and the "errorText" is the .
- /// Can be called multiple times: new error information replaces the previous one.
- ///
- /// The exception. Can not be null.
- void SetError( Exception ex );
- }
+ ///
+ /// Cancels the login and sets an error message.
+ /// The returned error has "errorId" set to the full name of the exception
+ /// and the "errorText" is the .
+ /// Can be called multiple times: new error information replaces the previous one.
+ ///
+ /// The exception. Can not be null.
+ void SetError( Exception ex );
}
diff --git a/CK.AspNet.Auth/Extensions/ValidateLogin/IWebFrontAuthValidateLoginService.cs b/CK.AspNet.Auth/Extensions/ValidateLogin/IWebFrontAuthValidateLoginService.cs
index b2393ead..13f79a02 100644
--- a/CK.AspNet.Auth/Extensions/ValidateLogin/IWebFrontAuthValidateLoginService.cs
+++ b/CK.AspNet.Auth/Extensions/ValidateLogin/IWebFrontAuthValidateLoginService.cs
@@ -7,35 +7,34 @@
using System.Text;
using System.Threading.Tasks;
-namespace CK.AspNet.Auth
+namespace CK.AspNet.Auth;
+
+///
+/// Optional service that, when registered, enables login validations.
+/// When this service is available, the login process follows the 3 steps below:
+///
+///
+/// First, the is called
+/// with a false actualLogin parameter.
+///
+///
+/// On success, this is called.
+///
+///
+/// Then, only if this validation succeeds, the
+/// is called again with a true actualLogin parameter.
+///
+///
+///
+[ContainerConfiguredSingletonService]
+public interface IWebFrontAuthValidateLoginService : ISingletonAutoService
{
///
- /// Optional service that, when registered, enables login validations.
- /// When this service is available, the login process follows the 3 steps below:
- ///
- ///
- /// First, the is called
- /// with a false actualLogin parameter.
- ///
- ///
- /// On success, this is called.
- ///
- ///
- /// Then, only if this validation succeeds, the
- /// is called again with a true actualLogin parameter.
- ///
- ///
+ /// Called for each login. Any error set on the cancels the login.
///
- [ContainerConfiguredSingletonService]
- public interface IWebFrontAuthValidateLoginService : ISingletonAutoService
- {
- ///
- /// Called for each login. Any error set on the cancels the login.
- ///
- /// The monitor to use.
- /// The logged in user.
- /// Validation context.
- /// The awaitable.
- Task ValidateLoginAsync( IActivityMonitor monitor, IUserInfo loggedInUser, IWebFrontAuthValidateLoginContext context );
- }
+ /// The monitor to use.
+ /// The logged in user.
+ /// Validation context.
+ /// The awaitable.
+ Task ValidateLoginAsync( IActivityMonitor monitor, IUserInfo loggedInUser, IWebFrontAuthValidateLoginContext context );
}
diff --git a/CK.AspNet.Auth/FrontAuthenticationInfo.cs b/CK.AspNet.Auth/FrontAuthenticationInfo.cs
index a2cedf76..aebdbe57 100644
--- a/CK.AspNet.Auth/FrontAuthenticationInfo.cs
+++ b/CK.AspNet.Auth/FrontAuthenticationInfo.cs
@@ -1,61 +1,60 @@
using CK.Auth;
-namespace CK.AspNet.Auth
+namespace CK.AspNet.Auth;
+
+///
+/// Immutable capture of the core along with option.
+/// This is the information that is stored in the token and the authentication cookie.
+///
+/// It's a reference type since it is stored in the HttpContext's Items (a struct would be boxed 99% of the times).
+///
+///
+public sealed class FrontAuthenticationInfo
{
///
- /// Immutable capture of the core along with option.
- /// This is the information that is stored in the token and the authentication cookie.
- ///
- /// It's a reference type since it is stored in the HttpContext's Items (a struct would be boxed 99% of the times).
- ///
+ /// The authentication information.
///
- public sealed class FrontAuthenticationInfo
- {
- ///
- /// The authentication information.
- ///
- public readonly IAuthenticationInfo Info;
+ public readonly IAuthenticationInfo Info;
- ///
- /// Whether this authentication info should be memorized or considered
- /// as a transient one.
- ///
- public readonly bool RememberMe;
+ ///
+ /// Whether this authentication info should be memorized or considered
+ /// as a transient one.
+ ///
+ public readonly bool RememberMe;
- ///
- /// Initializes a new info.
- ///
- /// The info.
- /// The option.
- public FrontAuthenticationInfo( IAuthenticationInfo info, bool rememberMe )
- {
- Info = info;
- RememberMe = rememberMe;
- }
+ ///
+ /// Initializes a new info.
+ ///
+ /// The info.
+ /// The option.
+ public FrontAuthenticationInfo( IAuthenticationInfo info, bool rememberMe )
+ {
+ Info = info;
+ RememberMe = rememberMe;
+ }
- ///
- /// Immutable setter.
- ///
- /// The new info to consider.
- /// The new front authentication info (or this).
- public FrontAuthenticationInfo SetInfo( IAuthenticationInfo info ) => info == Info ? this : new FrontAuthenticationInfo( info, RememberMe );
+ ///
+ /// Immutable setter.
+ ///
+ /// The new info to consider.
+ /// The new front authentication info (or this).
+ public FrontAuthenticationInfo SetInfo( IAuthenticationInfo info ) => info == Info ? this : new FrontAuthenticationInfo( info, RememberMe );
- ///
- /// Immutable setter.
- /// Ensures that is .
- /// The user identifier and name is available (but at the unsafe level). The device identifier
- /// and the flag are preserved. This is a kind of "soft logout".
- ///
- /// The new front authentication info (or this).
- public FrontAuthenticationInfo SetUnsafeLevel() => Info.Level <= AuthLevel.Unsafe
- ? this
- : new FrontAuthenticationInfo( Info.SetExpires( null ), RememberMe );
+ ///
+ /// Immutable setter.
+ /// Ensures that is .
+ /// The user identifier and name is available (but at the unsafe level). The device identifier
+ /// and the flag are preserved. This is a kind of "soft logout".
+ ///
+ /// The new front authentication info (or this).
+ public FrontAuthenticationInfo SetUnsafeLevel() => Info.Level <= AuthLevel.Unsafe
+ ? this
+ : new FrontAuthenticationInfo( Info.SetExpires( null ), RememberMe );
- ///
- /// Immutable setter.
- ///
- /// The new remember me.
- /// The new front authentication info (or this).
- public FrontAuthenticationInfo SetRememberMe( bool rememberMe ) => rememberMe == RememberMe ? this : new FrontAuthenticationInfo( Info, rememberMe );
- }
+ ///
+ /// Immutable setter.
+ ///
+ /// The new remember me.
+ /// The new front authentication info (or this).
+ public FrontAuthenticationInfo SetRememberMe( bool rememberMe ) => rememberMe == RememberMe ? this : new FrontAuthenticationInfo( Info, rememberMe );
}
diff --git a/CK.AspNet.Auth/IErrorContext.cs b/CK.AspNet.Auth/IErrorContext.cs
index 643d94d3..bc8b18cb 100644
--- a/CK.AspNet.Auth/IErrorContext.cs
+++ b/CK.AspNet.Auth/IErrorContext.cs
@@ -1,22 +1,20 @@
-namespace CK.AspNet.Auth
+namespace CK.AspNet.Auth;
+
+///
+/// Internal that unifies and .
+///
+interface IErrorContext
{
///
- /// Internal that unifies and .
+ /// Sets an error identifier and message.
+ /// Can be called multiple times: new error information replaces the previous one.
///
- interface IErrorContext
- {
- ///
- /// Sets an error identifier and message.
- /// Can be called multiple times: new error information replaces the previous one.
- ///
- /// Error identifier (a dotted identifier string).
- /// The error message in clear text.
- public void SetError( string errorId, string errorMessage );
-
- ///
- /// Gets whether an error has been set.
- ///
- bool HasError { get; }
- }
+ /// Error identifier (a dotted identifier string).
+ /// The error message in clear text.
+ public void SetError( string errorId, string errorMessage );
+ ///
+ /// Gets whether an error has been set.
+ ///
+ bool HasError { get; }
}
diff --git a/CK.AspNet.Auth/IWebFrontAuthLoginService.cs b/CK.AspNet.Auth/IWebFrontAuthLoginService.cs
index e5c6df23..ab81ad25 100644
--- a/CK.AspNet.Auth/IWebFrontAuthLoginService.cs
+++ b/CK.AspNet.Auth/IWebFrontAuthLoginService.cs
@@ -6,80 +6,79 @@
using System.Text;
using System.Threading.Tasks;
-namespace CK.AspNet.Auth
+namespace CK.AspNet.Auth;
+
+///
+/// Interface to the back-end login service.
+/// This is the most important (and required) service that abstracts any persistence layer or gateway that
+/// is able to handle login and authentication.
+///
+/// This service is a endpoint service: it is available only in the global DI context, not from any other endpoints.
+///
+///
+[ContainerConfiguredSingletonService]
+public interface IWebFrontAuthLoginService : ISingletonAutoService
{
///
- /// Interface to the back-end login service.
- /// This is the most important (and required) service that abstracts any persistence layer or gateway that
- /// is able to handle login and authentication.
- ///
- /// This service is a endpoint service: it is available only in the global DI context, not from any other endpoints.
- ///
+ /// Gets whether is supported.
///
- [ContainerConfiguredSingletonService]
- public interface IWebFrontAuthLoginService : ISingletonAutoService
- {
- ///
- /// Gets whether is supported.
- ///
- bool HasBasicLogin { get; }
+ bool HasBasicLogin { get; }
- ///
- /// Gets the existing providers's name.
- ///
- IReadOnlyList Providers { get; }
+ ///
+ /// Gets the existing providers's name.
+ ///
+ IReadOnlyList Providers { get; }
- ///
- /// Attempts to login. must be true for this
- /// to be called. Must never return null.
- ///
- /// Current Http context.
- /// The activity monitor to use.
- /// The user name.
- /// The password.
- ///
- /// Set it to false to avoid login side-effect (such as updating the LastLoginTime) on success:
- /// only checks are done.
- ///
- /// A non null .
- Task BasicLoginAsync( HttpContext ctx, IActivityMonitor monitor, string userName, string password, bool actualLogin = true );
+ ///
+ /// Attempts to login. must be true for this
+ /// to be called. Must never return null.
+ ///
+ /// Current Http context.
+ /// The activity monitor to use.
+ /// The user name.
+ /// The password.
+ ///
+ /// Set it to false to avoid login side-effect (such as updating the LastLoginTime) on success:
+ /// only checks are done.
+ ///
+ /// A non null .
+ Task BasicLoginAsync( HttpContext ctx, IActivityMonitor monitor, string userName, string password, bool actualLogin = true );
- ///
- /// Creates a payload object for a given scheme that can be used to
- /// call .
- ///
- /// Current Http context.
- /// The activity monitor to use.
- /// The login scheme (either the provider name to use or starts with the provider name and a dot).
- /// A new, empty, provider dependent login payload.
- object CreatePayload( HttpContext ctx, IActivityMonitor monitor, string scheme );
+ ///
+ /// Creates a payload object for a given scheme that can be used to
+ /// call .
+ ///
+ /// Current Http context.
+ /// The activity monitor to use.
+ /// The login scheme (either the provider name to use or starts with the provider name and a dot).
+ /// A new, empty, provider dependent login payload.
+ object CreatePayload( HttpContext ctx, IActivityMonitor monitor, string scheme );
- ///
- /// Attempts to login a user using an existing provider.
- /// The provider derived from the scheme must exist and the payload must be compatible
- /// otherwise an is thrown.
- /// Must never return null.
- ///
- /// Current Http context.
- /// The activity monitor to use.
- /// The login scheme (either the provider name to use or starts with the provider name and a dotted suffix).
- /// The provider dependent login payload.
- ///
- /// Set it to false to avoid login side-effect (such as updating the LastLoginTime) on success:
- /// only checks are done.
- ///
- /// A non null .
- Task LoginAsync( HttpContext ctx, IActivityMonitor monitor, string scheme, object payload, bool actualLogin = true );
+ ///
+ /// Attempts to login a user using an existing provider.
+ /// The provider derived from the scheme must exist and the payload must be compatible
+ /// otherwise an is thrown.
+ /// Must never return null.
+ ///
+ /// Current Http context.
+ /// The activity monitor to use.
+ /// The login scheme (either the provider name to use or starts with the provider name and a dotted suffix).
+ /// The provider dependent login payload.
+ ///
+ /// Set it to false to avoid login side-effect (such as updating the LastLoginTime) on success:
+ /// only checks are done.
+ ///
+ /// A non null .
+ Task LoginAsync( HttpContext ctx, IActivityMonitor monitor, string scheme, object payload, bool actualLogin = true );
- ///
- /// Refreshes a by reading the actual user and the impersonated user if any.
- ///
- /// The current http context.
- /// The monitor to use.
- /// The current authentication info that should be refreshed. Can be null (None authentication is returned).
- /// New expiration date (can be the same as the current's one).
- /// The refreshed information. Never null but may be the None authentication info.
- Task RefreshAuthenticationInfoAsync( HttpContext ctx, IActivityMonitor monitor, IAuthenticationInfo current, DateTime newExpires );
+ ///
+ /// Refreshes a by reading the actual user and the impersonated user if any.
+ ///
+ /// The current http context.
+ /// The monitor to use.
+ /// The current authentication info that should be refreshed. Can be null (None authentication is returned).
+ /// New expiration date (can be the same as the current's one).
+ /// The refreshed information. Never null but may be the None authentication info.
+ Task RefreshAuthenticationInfoAsync( HttpContext ctx, IActivityMonitor monitor, IAuthenticationInfo current, DateTime newExpires );
- }
}
diff --git a/CK.AspNet.Auth/InternalExtensions.cs b/CK.AspNet.Auth/InternalExtensions.cs
index b748a572..f85b7c2a 100644
--- a/CK.AspNet.Auth/InternalExtensions.cs
+++ b/CK.AspNet.Auth/InternalExtensions.cs
@@ -10,58 +10,58 @@
using System.Text;
using System.Threading.Tasks;
-namespace CK.AspNet.Auth
+namespace CK.AspNet.Auth;
+
+static class InternalExtensions
{
- static class InternalExtensions
+ static public JProperty ToJProperty( this IDictionary @this, string name = "userData" )
{
- static public JProperty ToJProperty( this IDictionary @this, string name = "userData" )
- {
- return new JProperty( name,
- new JObject( @this.Select( d => new JProperty( d.Key, (string?)d.Value ) ) ) );
- }
+ return new JProperty( name,
+ new JObject( @this.Select( d => new JProperty( d.Key, (string?)d.Value ) ) ) );
+ }
- static public void SetNoCacheAndDefaultStatus( this HttpResponse @this, int defaultStatusCode )
- {
- @this.Headers[HeaderNames.CacheControl] = "no-cache";
- @this.Headers[HeaderNames.Pragma] = "no-cache";
- @this.Headers[HeaderNames.Expires] = "-1";
- @this.StatusCode = defaultStatusCode;
- }
+ static public void SetNoCacheAndDefaultStatus( this HttpResponse @this, int defaultStatusCode )
+ {
+ @this.Headers[HeaderNames.CacheControl] = "no-cache";
+ @this.Headers[HeaderNames.Pragma] = "no-cache";
+ @this.Headers[HeaderNames.Expires] = "-1";
+ @this.StatusCode = defaultStatusCode;
+ }
- ///
- /// Reads a limited number of characters from the request body (with an UTF8 encoding).
- ///
- /// This request.
- /// The maximal number of characters to read.
- /// The string or null on error.
- static public async Task TryReadSmallBodyAsStringAsync( this HttpRequest @this, int maxLen )
+ ///
+ /// Reads a limited number of characters from the request body (with an UTF8 encoding).
+ ///
+ /// This request.
+ /// The maximal number of characters to read.
+ /// The string or null on error.
+ static public async Task TryReadSmallBodyAsStringAsync( this HttpRequest @this, int maxLen )
+ {
+ using( var s = new StreamReader( @this.Body, Encoding.UTF8, true, 1024, true ) )
{
- using( var s = new StreamReader( @this.Body, Encoding.UTF8, true, 1024, true ) )
+ char[] max = new char[maxLen + 1];
+ int len = await s.ReadBlockAsync( max, 0, maxLen + 1 );
+ if( len >= maxLen )
{
- char[] max = new char[maxLen + 1];
- int len = await s.ReadBlockAsync( max, 0, maxLen + 1 );
- if( len >= maxLen )
- {
- @this.HttpContext.Response.StatusCode = StatusCodes.Status400BadRequest;
- return null;
- }
- return new String( max, 0, len );
+ @this.HttpContext.Response.StatusCode = StatusCodes.Status400BadRequest;
+ return null;
}
+ return new String( max, 0, len );
}
+ }
- static public Task WriteAsync( this HttpResponse @this, JObject? o, int code = StatusCodes.Status200OK )
- {
- @this.StatusCode = code;
- @this.ContentType = "application/json";
- return @this.WriteAsync( o != null ? o.ToString( Newtonsoft.Json.Formatting.None ) : "{}" );
- }
+ static public Task WriteAsync( this HttpResponse @this, JObject? o, int code = StatusCodes.Status200OK )
+ {
+ @this.StatusCode = code;
+ @this.ContentType = "application/json";
+ return @this.WriteAsync( o != null ? o.ToString( Newtonsoft.Json.Formatting.None ) : "{}" );
+ }
- static public Task WriteWindowPostMessageAsync( this HttpResponse @this, JObject o, string? callerOrigin )
- {
- @this.StatusCode = StatusCodes.Status200OK;
- @this.ContentType = "text/html";
- var oS = o != null ? o.ToString( Newtonsoft.Json.Formatting.None ) : "{}";
- var r = $@"
+ static public Task WriteWindowPostMessageAsync( this HttpResponse @this, JObject o, string? callerOrigin )
+ {
+ @this.StatusCode = StatusCodes.Status200OK;
+ @this.ContentType = "text/html";
+ var oS = o != null ? o.ToString( Newtonsoft.Json.Formatting.None ) : "{}";
+ var r = $@"
@@ -78,15 +78,14 @@ static public Task WriteWindowPostMessageAsync( this HttpResponse @this, JObject
";
- return @this.WriteAsync( r );
- }
+ return @this.WriteAsync( r );
+ }
- static string GetBreachPadding()
- {
- Random random = new Random();
- byte[] data = new byte[random.Next( 10, 256 )];
- random.NextBytes( data );
- return Convert.ToBase64String( data );
- }
+ static string GetBreachPadding()
+ {
+ Random random = new Random();
+ byte[] data = new byte[random.Next( 10, 256 )];
+ random.NextBytes( data );
+ return Convert.ToBase64String( data );
}
}
diff --git a/CK.AspNet.Auth/RemoteAuthenticationEventsContextExtensions.cs b/CK.AspNet.Auth/RemoteAuthenticationEventsContextExtensions.cs
index 0f22dd6e..fd0c976d 100644
--- a/CK.AspNet.Auth/RemoteAuthenticationEventsContextExtensions.cs
+++ b/CK.AspNet.Auth/RemoteAuthenticationEventsContextExtensions.cs
@@ -5,124 +5,123 @@
using System;
using System.Threading.Tasks;
-namespace CK.AspNet.Auth
+namespace CK.AspNet.Auth;
+
+///
+/// Helper on and .
+///
+public static class RemoteAuthenticationEventsContextExtensions
{
///
- /// Helper on and .
+ /// Obsolete.
///
- public static class RemoteAuthenticationEventsContextExtensions
- {
- ///
- /// Obsolete.
- ///
- /// Type of the payload.
- /// This ticket received context.
- /// Action that must configure the payload.
- /// The awaitable.
- [Obsolete( "Use WebFrontAuthOnTicketReceivedAsync (renaming).", error: true )]
- public static Task WebFrontAuthRemoteAuthenticateAsync( this TicketReceivedContext c, Action payloadConfigurator )
- => WebFrontAuthOnTicketReceivedAsync( c, payloadConfigurator );
+ /// Type of the payload.
+ /// This ticket received context.
+ /// Action that must configure the payload.
+ /// The awaitable.
+ [Obsolete( "Use WebFrontAuthOnTicketReceivedAsync (renaming).", error: true )]
+ public static Task WebFrontAuthRemoteAuthenticateAsync( this TicketReceivedContext c, Action payloadConfigurator )
+ => WebFrontAuthOnTicketReceivedAsync( c, payloadConfigurator );
- ///
- /// Simple API used from to handle
- /// external authentication:
- /// is called.
- ///
- /// Type of the payload.
- /// This ticket received context.
- /// Action that must configure the payload.
- /// The awaitable.
- public static Task WebFrontAuthOnTicketReceivedAsync( this TicketReceivedContext c, Action payloadConfigurator )
- {
- var authService = c.HttpContext.RequestServices.GetRequiredService();
- return authService.HandleRemoteAuthenticationAsync( c, payloadConfigurator );
- }
+ ///
+ /// Simple API used from to handle
+ /// external authentication:
+ /// is called.
+ ///
+ /// Type of the payload.
+ /// This ticket received context.
+ /// Action that must configure the payload.
+ /// The awaitable.
+ public static Task WebFrontAuthOnTicketReceivedAsync( this TicketReceivedContext c, Action payloadConfigurator )
+ {
+ var authService = c.HttpContext.RequestServices.GetRequiredService();
+ return authService.HandleRemoteAuthenticationAsync( c, payloadConfigurator );
+ }
- ///
- /// Simple API used from to handle remote failure authentication:
- /// the and are returned to the client.
- /// (This method calls that ends any further response processing.)
- ///
- /// This remote failure context.
- ///
- /// True to downgrade the current authentication to .
- /// By default the current authentication is kept as-is.
- ///
- ///
- /// Error identifier: should be a dotted identifier that could easily be used as a resource
- /// name (to map to translations in different languages).
- ///
- /// When null, 's is used.
- /// The awaitable.
- public static Task WebFrontAuthOnRemoteFailureAsync( this RemoteFailureContext f, bool setUnsafeLevel = false, string errorId = "RemoteFailure", string? errorText = null )
- {
- return OnErrorAsync( f, f.Properties, setUnsafeLevel, errorId, errorText ?? f.Failure?.Message ?? "RemoteFailure" );
- }
+ ///
+ /// Simple API used from to handle remote failure authentication:
+ /// the and are returned to the client.
+ /// (This method calls that ends any further response processing.)
+ ///
+ /// This remote failure context.
+ ///
+ /// True to downgrade the current authentication to .
+ /// By default the current authentication is kept as-is.
+ ///
+ ///
+ /// Error identifier: should be a dotted identifier that could easily be used as a resource
+ /// name (to map to translations in different languages).
+ ///
+ /// When null, 's is used.
+ /// The awaitable.
+ public static Task WebFrontAuthOnRemoteFailureAsync( this RemoteFailureContext f, bool setUnsafeLevel = false, string errorId = "RemoteFailure", string? errorText = null )
+ {
+ return OnErrorAsync( f, f.Properties, setUnsafeLevel, errorId, errorText ?? f.Failure?.Message ?? "RemoteFailure" );
+ }
- ///
- /// Simple API used from to handle remote access denied:
- /// the and are returned to the client.
- /// (This method calls that ends any further response processing.)
- ///
- /// This remote failure context.
- ///
- /// True to downgrade the current authentication to .
- /// By default the current authentication is kept as-is.
- ///
- ///
- /// Error identifier: should be a dotted identifier that could easily be used as a resource
- /// name (to map to translations in different languages).
- ///
- /// When null, is used.
- /// The awaitable.
- public static Task WebFrontAuthOnAccessDeniedAsync( this AccessDeniedContext d,
- bool setUnsafeLevel = false,
- string errorId = "AccessDenied",
- string? errorText = null )
- {
- return OnErrorAsync( d, d.Properties, setUnsafeLevel, errorId, errorText ?? errorId );
- }
+ ///
+ /// Simple API used from to handle remote access denied:
+ /// the and are returned to the client.
+ /// (This method calls that ends any further response processing.)
+ ///
+ /// This remote failure context.
+ ///
+ /// True to downgrade the current authentication to .
+ /// By default the current authentication is kept as-is.
+ ///
+ ///
+ /// Error identifier: should be a dotted identifier that could easily be used as a resource
+ /// name (to map to translations in different languages).
+ ///
+ /// When null, is used.
+ /// The awaitable.
+ public static Task WebFrontAuthOnAccessDeniedAsync( this AccessDeniedContext d,
+ bool setUnsafeLevel = false,
+ string errorId = "AccessDenied",
+ string? errorText = null )
+ {
+ return OnErrorAsync( d, d.Properties, setUnsafeLevel, errorId, errorText ?? errorId );
+ }
- static Task OnErrorAsync( HandleRequestContext h,
- AuthenticationProperties? properties,
- bool setUnsafeLevel,
- string errorId,
- string errorText )
+ static Task OnErrorAsync( HandleRequestContext h,
+ AuthenticationProperties? properties,
+ bool setUnsafeLevel,
+ string errorId,
+ string errorText )
+ {
+ h.HandleResponse();
+ var authService = h.HttpContext.RequestServices.GetRequiredService();
+ authService.GetWFAData( h.HttpContext, properties, out var fAuth, out var impersonateActualUser, out var initialScheme, out var callerOrigin, out var returnUrl, out var userData );
+ if( setUnsafeLevel )
{
- h.HandleResponse();
- var authService = h.HttpContext.RequestServices.GetRequiredService();
- authService.GetWFAData( h.HttpContext, properties, out var fAuth, out var impersonateActualUser, out var initialScheme, out var callerOrigin, out var returnUrl, out var userData );
- if( setUnsafeLevel )
- {
- fAuth = fAuth.SetUnsafeLevel();
- }
- return authService.SendRemoteAuthenticationErrorAsync( h.HttpContext, fAuth, returnUrl, callerOrigin, errorId, errorText, initialScheme, h.Scheme.Name, userData );
+ fAuth = fAuth.SetUnsafeLevel();
}
+ return authService.SendRemoteAuthenticationErrorAsync( h.HttpContext, fAuth, returnUrl, callerOrigin, errorId, errorText, initialScheme, h.Scheme.Name, userData );
+ }
- ///
- /// Extracts the initial authentication from this context (from the "WFA-C" key of ).
- ///
- /// This ticket received context.
- /// The initial authentication.
- public static IAuthenticationInfo GetTicketAuthenticationInfo( this TicketReceivedContext @this ) => GetFrontAuthenticationInfo( @this.HttpContext, @this.Properties ).Info;
+ ///
+ /// Extracts the initial authentication from this context (from the "WFA-C" key of ).
+ ///
+ /// This ticket received context.
+ /// The initial authentication.
+ public static IAuthenticationInfo GetTicketAuthenticationInfo( this TicketReceivedContext @this ) => GetFrontAuthenticationInfo( @this.HttpContext, @this.Properties ).Info;
- ///
- /// Extracts the initial authentication from this context (from the "WFA-C" key of ).
- ///
- /// This failure context.
- /// The initial authentication.
- public static IAuthenticationInfo GetTicketAuthenticationInfo( this RemoteFailureContext @this ) => GetFrontAuthenticationInfo( @this.HttpContext, @this.Properties ).Info;
+ ///
+ /// Extracts the initial authentication from this context (from the "WFA-C" key of ).
+ ///
+ /// This failure context.
+ /// The initial authentication.
+ public static IAuthenticationInfo GetTicketAuthenticationInfo( this RemoteFailureContext @this ) => GetFrontAuthenticationInfo( @this.HttpContext, @this.Properties ).Info;
- ///
- /// Extracts the initial authentication from this context (from the "WFA-C" key of ).
- ///
- /// This failure context.
- /// The initial authentication.
- public static IAuthenticationInfo GetTicketAuthenticationInfo( this AccessDeniedContext d ) => GetFrontAuthenticationInfo( d.HttpContext, d.Properties ).Info;
+ ///
+ /// Extracts the initial authentication from this context (from the "WFA-C" key of ).
+ ///
+ /// This failure context.
+ /// The initial authentication.
+ public static IAuthenticationInfo GetTicketAuthenticationInfo( this AccessDeniedContext d ) => GetFrontAuthenticationInfo( d.HttpContext, d.Properties ).Info;
- static FrontAuthenticationInfo GetFrontAuthenticationInfo( HttpContext httpContext, AuthenticationProperties? properties )
- {
- return httpContext.RequestServices.GetRequiredService().GetFrontAuthenticationInfo( httpContext, properties );
- }
+ static FrontAuthenticationInfo GetFrontAuthenticationInfo( HttpContext httpContext, AuthenticationProperties? properties )
+ {
+ return httpContext.RequestServices.GetRequiredService().GetFrontAuthenticationInfo( httpContext, properties );
}
}
diff --git a/CK.AspNet.Auth/SecureData/ExtraDataSecureDataFormat.cs b/CK.AspNet.Auth/SecureData/ExtraDataSecureDataFormat.cs
index e9f0087e..3da3d17e 100644
--- a/CK.AspNet.Auth/SecureData/ExtraDataSecureDataFormat.cs
+++ b/CK.AspNet.Auth/SecureData/ExtraDataSecureDataFormat.cs
@@ -9,56 +9,54 @@
using System.IO;
using System.Text;
-namespace CK.AspNet.Auth
+namespace CK.AspNet.Auth;
+
+///
+/// Secure IQueryCollection and/or IFormCollection data serialization, using a binary serialization.
+///
+public class ExtraDataSecureDataFormat : SecureDataFormat>
{
- ///
- /// Secure IQueryCollection and/or IFormCollection data serialization, using a binary serialization.
- ///
- public class ExtraDataSecureDataFormat : SecureDataFormat>
+ class Serializer : IDataSerializer>
{
- class Serializer : IDataSerializer>
+ public IDictionary Deserialize( byte[] data )
{
- public IDictionary Deserialize( byte[] data )
+ var result = new Dictionary();
+ using( var s = Util.RecyclableStreamManager.GetStream( data ) )
+ using( var r = new CKBinaryReader( s ) )
{
- var result = new Dictionary();
- using( var s = Util.RecyclableStreamManager.GetStream( data ) )
- using( var r = new CKBinaryReader( s ) )
+ int c = r.ReadNonNegativeSmallInt32();
+ while( --c >= 0 )
{
- int c = r.ReadNonNegativeSmallInt32();
- while( --c >= 0 )
- {
- result.Add( r.ReadString(), r.ReadNullableString() );
- }
- return result;
+ result.Add( r.ReadString(), r.ReadNullableString() );
}
+ return result;
}
+ }
- public byte[] Serialize( IDictionary model )
+ public byte[] Serialize( IDictionary model )
+ {
+ using( var s = Util.RecyclableStreamManager.GetStream() )
+ using( var w = new CKBinaryWriter( s ) )
{
- using( var s = Util.RecyclableStreamManager.GetStream() )
- using( var w = new CKBinaryWriter( s ) )
+ w.WriteNonNegativeSmallInt32( model.Count );
+ foreach( var k in model )
{
- w.WriteNonNegativeSmallInt32( model.Count );
- foreach( var k in model )
- {
- w.Write( k.Key );
- w.WriteNullableString( k.Value );
- }
- return s.ToArray();
+ w.Write( k.Key );
+ w.WriteNullableString( k.Value );
}
+ return s.ToArray();
}
}
+ }
- static readonly Serializer _serializer = new Serializer();
+ static readonly Serializer _serializer = new Serializer();
- ///
- /// Initialize a new AuthenticationInfoSecureDataFormat.
- ///
- /// Data protector to use.
- public ExtraDataSecureDataFormat( IDataProtector p )
- : base( _serializer, p )
- {
- }
+ ///
+ /// Initialize a new AuthenticationInfoSecureDataFormat.
+ ///
+ /// Data protector to use.
+ public ExtraDataSecureDataFormat( IDataProtector p )
+ : base( _serializer, p )
+ {
}
-
}
diff --git a/CK.AspNet.Auth/SecureData/FrontAuthenticationInfoSecureDataFormat.cs b/CK.AspNet.Auth/SecureData/FrontAuthenticationInfoSecureDataFormat.cs
index d861d7b3..b1a2f423 100644
--- a/CK.AspNet.Auth/SecureData/FrontAuthenticationInfoSecureDataFormat.cs
+++ b/CK.AspNet.Auth/SecureData/FrontAuthenticationInfoSecureDataFormat.cs
@@ -7,54 +7,52 @@
using System.IO;
using System.Text;
-namespace CK.AspNet.Auth
+namespace CK.AspNet.Auth;
+
+///
+/// Secure data, using a binary serialization
+/// thanks to .
+///
+class FrontAuthenticationInfoSecureDataFormat : SecureDataFormat
{
- ///
- /// Secure data, using a binary serialization
- /// thanks to .
- ///
- class FrontAuthenticationInfoSecureDataFormat : SecureDataFormat
+ class Serializer : IDataSerializer
{
- class Serializer : IDataSerializer
- {
- readonly IAuthenticationInfoType _t;
+ readonly IAuthenticationInfoType _t;
- public Serializer( IAuthenticationTypeSystem t )
- {
- _t = t.AuthenticationInfo;
- }
+ public Serializer( IAuthenticationTypeSystem t )
+ {
+ _t = t.AuthenticationInfo;
+ }
- public FrontAuthenticationInfo Deserialize( byte[] data )
+ public FrontAuthenticationInfo Deserialize( byte[] data )
+ {
+ using( var s = Util.RecyclableStreamManager.GetStream( data ) )
+ using( var r = new BinaryReader( s ) )
{
- using( var s = Util.RecyclableStreamManager.GetStream( data ) )
- using( var r = new BinaryReader( s ) )
- {
- return new FrontAuthenticationInfo( _t.Read( r )!, r.ReadBoolean() );
- }
+ return new FrontAuthenticationInfo( _t.Read( r )!, r.ReadBoolean() );
}
+ }
- public byte[] Serialize( FrontAuthenticationInfo model )
+ public byte[] Serialize( FrontAuthenticationInfo model )
+ {
+ using( var s = Util.RecyclableStreamManager.GetStream() )
+ using( var w = new BinaryWriter( s ) )
{
- using( var s = Util.RecyclableStreamManager.GetStream() )
- using( var w = new BinaryWriter( s ) )
- {
- _t.Write( w, model.Info );
- w.Write( model.RememberMe );
- return s.ToArray();
- }
+ _t.Write( w, model.Info );
+ w.Write( model.RememberMe );
+ return s.ToArray();
}
}
+ }
- ///
- /// Initialize a new AuthenticationInfoSecureDataFormat.
- ///
- /// Type system to use.
- /// Data protector to use.
- public FrontAuthenticationInfoSecureDataFormat( IAuthenticationTypeSystem t, IDataProtector p )
- : base( new Serializer( t ), p )
+ ///
+ /// Initialize a new AuthenticationInfoSecureDataFormat.
+ ///
+ /// Type system to use.
+ /// Data protector to use.
+ public FrontAuthenticationInfoSecureDataFormat( IAuthenticationTypeSystem t, IDataProtector p )
+ : base( new Serializer( t ), p )
- {
- }
+ {
}
-
}
diff --git a/CK.AspNet.Auth/UserLoginResult.cs b/CK.AspNet.Auth/UserLoginResult.cs
index 68fa9473..54ae3df8 100644
--- a/CK.AspNet.Auth/UserLoginResult.cs
+++ b/CK.AspNet.Auth/UserLoginResult.cs
@@ -4,91 +4,90 @@
using System.Diagnostics.CodeAnalysis;
using System.Text;
-namespace CK.AspNet.Auth
+namespace CK.AspNet.Auth;
+
+///
+/// Encapsulates login result information.
+///
+public class UserLoginResult
{
///
- /// Encapsulates login result information.
+ /// Initializes a new login result.
///
- public class UserLoginResult
+ /// The user info. When null or anonymous, failure code and reason must indicate an error.
+ ///
+ /// Failure code must be positive on failure, zero on success.
+ /// Standard implementation by CK.DB.AspNetAuth (the SqlWebFrontAuthLoginService class) uses
+ /// the CK.DB.Auth.KnownLoginFailureCode that is defined here: https://github.com/Invenietis/CK-DB/blob/develop/CK.DB.Auth/KnownLoginFailureCode.cs.
+ ///
+ /// Failure reason must be not null on failure, null on success.
+ ///
+ /// Indicates that the login failed because the user is not registered in the provider: this may be
+ /// corrected by registering the user for the provider.
+ /// This can be true only on failure otherwise an argument exception is thrown.
+ ///
+ public UserLoginResult( IUserInfo? info, int failureCode, string? failureReason, bool unregisteredUser )
{
- ///
- /// Initializes a new login result.
- ///
- /// The user info. When null or anonymous, failure code and reason must indicate an error.
- ///
- /// Failure code must be positive on failure, zero on success.
- /// Standard implementation by CK.DB.AspNetAuth (the SqlWebFrontAuthLoginService class) uses
- /// the CK.DB.Auth.KnownLoginFailureCode that is defined here: https://github.com/Invenietis/CK-DB/blob/develop/CK.DB.Auth/KnownLoginFailureCode.cs.
- ///
- /// Failure reason must be not null on failure, null on success.
- ///
- /// Indicates that the login failed because the user is not registered in the provider: this may be
- /// corrected by registering the user for the provider.
- /// This can be true only on failure otherwise an argument exception is thrown.
- ///
- public UserLoginResult( IUserInfo? info, int failureCode, string? failureReason, bool unregisteredUser )
+ if( info == null || info.UserId == 0 )
{
- if( info == null || info.UserId == 0 )
+ if( failureReason == null )
{
- if( failureReason == null )
- {
- throw new ArgumentException( $"Null or anonymous: failure reason must be not null.", nameof(failureReason) );
- }
- if( failureCode <= 0 )
- {
- throw new ArgumentException( $"Null or anonymous: failure code must be positive (value: {failureCode}).", nameof(failureCode) );
- }
- LoginFailureCode = failureCode;
- LoginFailureReason = failureReason;
- IsUnregisteredUser = unregisteredUser;
+ throw new ArgumentException( $"Null or anonymous: failure reason must be not null.", nameof( failureReason ) );
}
- else
+ if( failureCode <= 0 )
{
- if( failureReason != null )
- {
- throw new ArgumentException( $"Valid user info: failure reason must be null (value: {failureReason}).", nameof( failureReason ) );
- }
- if( failureCode != 0 )
- {
- throw new ArgumentException( $"Valid user info: : failure code must be zero (value: {failureCode}).", nameof( failureCode ) );
- }
- if( unregisteredUser )
- {
- throw new ArgumentException( $"Valid user info: it can not be an unregistered user.", nameof( unregisteredUser ) );
- }
- UserInfo = info;
+ throw new ArgumentException( $"Null or anonymous: failure code must be positive (value: {failureCode}).", nameof( failureCode ) );
}
+ LoginFailureCode = failureCode;
+ LoginFailureReason = failureReason;
+ IsUnregisteredUser = unregisteredUser;
}
+ else
+ {
+ if( failureReason != null )
+ {
+ throw new ArgumentException( $"Valid user info: failure reason must be null (value: {failureReason}).", nameof( failureReason ) );
+ }
+ if( failureCode != 0 )
+ {
+ throw new ArgumentException( $"Valid user info: : failure code must be zero (value: {failureCode}).", nameof( failureCode ) );
+ }
+ if( unregisteredUser )
+ {
+ throw new ArgumentException( $"Valid user info: it can not be an unregistered user.", nameof( unregisteredUser ) );
+ }
+ UserInfo = info;
+ }
+ }
- ///
- /// Gets the user information.
- /// Null if for any reason, login failed.
- ///
- public IUserInfo? UserInfo { get; }
+ ///
+ /// Gets the user information.
+ /// Null if for any reason, login failed.
+ ///
+ public IUserInfo? UserInfo { get; }
- ///
- /// Gets whether the login succeeded.
- ///
- [MemberNotNullWhen(true,nameof(UserInfo))]
- public bool IsSuccess => UserInfo != null;
+ ///
+ /// Gets whether the login succeeded.
+ ///
+ [MemberNotNullWhen( true, nameof( UserInfo ) )]
+ public bool IsSuccess => UserInfo != null;
- ///
- /// Gets whether the failure may be corrected by registering the user
- /// for the provider.
- ///
- public bool IsUnregisteredUser { get; }
+ ///
+ /// Gets whether the failure may be corrected by registering the user
+ /// for the provider.
+ ///
+ public bool IsUnregisteredUser { get; }
- ///
- /// Gets the login failure code. This value is positive if login failed.
- /// Standard implementation by CK.DB.AspNetAuth (the SqlWebFrontAuthLoginService class) uses
- /// the CK.DB.Auth.KnownLoginFailureCode that is defined here: https://github.com/Invenietis/CK-DB/blob/develop/CK.DB.Auth/KnownLoginFailureCode.cs.
- ///
- public int LoginFailureCode { get; }
+ ///
+ /// Gets the login failure code. This value is positive if login failed.
+ /// Standard implementation by CK.DB.AspNetAuth (the SqlWebFrontAuthLoginService class) uses
+ /// the CK.DB.Auth.KnownLoginFailureCode that is defined here: https://github.com/Invenietis/CK-DB/blob/develop/CK.DB.Auth/KnownLoginFailureCode.cs.
+ ///
+ public int LoginFailureCode { get; }
- ///
- /// Gets a string describing the reason of a login failure.
- /// Null on success.
- ///
- public string? LoginFailureReason { get; }
- }
+ ///
+ /// Gets a string describing the reason of a login failure.
+ /// Null on success.
+ ///
+ public string? LoginFailureReason { get; }
}
diff --git a/CK.AspNet.Auth/WebFrontAuthExtensions.cs b/CK.AspNet.Auth/WebFrontAuthExtensions.cs
index cf06a451..42638621 100644
--- a/CK.AspNet.Auth/WebFrontAuthExtensions.cs
+++ b/CK.AspNet.Auth/WebFrontAuthExtensions.cs
@@ -12,135 +12,134 @@
using System;
using System.Collections.Generic;
-namespace Microsoft.Extensions.DependencyInjection
+namespace Microsoft.Extensions.DependencyInjection;
+
+///
+/// Offers support for WebFrontAuth on .
+///
+public static class WebFrontAuthExtensions
{
///
- /// Offers support for WebFrontAuth on .
+ /// Idempotent registration of the , and
+ /// with the .
+ ///
+ /// When called more than once, all are applied to the final .
+ ///
///
- public static class WebFrontAuthExtensions
+ /// This builder.
+ /// Optional option configuration.
+ /// This builder.
+ public static WebApplicationBuilder AddWebFrontAuth( this WebApplicationBuilder builder,
+ Action? authOptions = null )
{
- ///
- /// Idempotent registration of the , and
- /// with the .
- ///
- /// When called more than once, all are applied to the final .
- ///
- ///
- /// This builder.
- /// Optional option configuration.
- /// This builder.
- public static WebApplicationBuilder AddWebFrontAuth( this WebApplicationBuilder builder,
- Action? authOptions = null )
+ var props = ((IHostApplicationBuilder)builder).Properties;
+ if( props.TryAdd( typeof( WebFrontAuthExtensions ), typeof( WebFrontAuthExtensions ) ) )
{
- var props = ((IHostApplicationBuilder)builder).Properties;
- if( props.TryAdd( typeof( WebFrontAuthExtensions ), typeof( WebFrontAuthExtensions ) ) )
- {
- builder.Services.AddSingleton();
- builder.Services.AddScoped( sp => sp.GetRequiredService().HttpContext.GetAuthenticationInfo() );
- var authBuilder = builder.Services.AddAuthentication( WebFrontAuthOptions.OnlyAuthenticationScheme );
- authBuilder.AddScheme( WebFrontAuthOptions.OnlyAuthenticationScheme, "Web Front Authentication", authOptions );
- builder.AppendApplicationBuilder( app => app.UseAuthentication() );
- }
- else if( authOptions != null )
- {
- // Already called. If an option configurator is present, register the new one.
- // The OptionsFactory will call all the registered IConfigureOptions.
- var configurator = new ConfigureNamedOptions( WebFrontAuthOptions.OnlyAuthenticationScheme, authOptions );
- builder.Services.AddSingleton>( configurator );
- }
- return builder;
+ builder.Services.AddSingleton();
+ builder.Services.AddScoped( sp => sp.GetRequiredService().HttpContext.GetAuthenticationInfo() );
+ var authBuilder = builder.Services.AddAuthentication( WebFrontAuthOptions.OnlyAuthenticationScheme );
+ authBuilder.AddScheme( WebFrontAuthOptions.OnlyAuthenticationScheme, "Web Front Authentication", authOptions );
+ builder.AppendApplicationBuilder( app => app.UseAuthentication() );
}
-
- ///
- /// Add dangerous Cors support: this allows all orgigins, methods, headers AND supports credential.
- /// This is unfortunately required in some testing scenario but should NEVER be used in production.
- ///
- /// This method, just like and
- /// can be called multiple times: the last wins.
- ///
- ///
- /// This builder.
- /// This builder.
- public static WebApplicationBuilder AddUnsafeAllowAllCors( this WebApplicationBuilder builder )
+ else if( authOptions != null )
{
- return AddCors( builder, CorsAllowAllBuilder );
-
- static void CorsAllowAllBuilder( CorsPolicyBuilder o )
- {
- o.AllowAnyMethod().AllowCredentials().AllowAnyHeader().SetIsOriginAllowed( _ => true );
- }
+ // Already called. If an option configurator is present, register the new one.
+ // The OptionsFactory will call all the registered IConfigureOptions.
+ var configurator = new ConfigureNamedOptions( WebFrontAuthOptions.OnlyAuthenticationScheme, authOptions );
+ builder.Services.AddSingleton>( configurator );
}
+ return builder;
+ }
- ///
- /// Add Cors support for a single policy.
- ///
- /// This method, just like and
- /// can be called multiple times: the last wins.
- ///
- ///
- /// This builder.
- /// The cors policy builder.
- ///
- public static WebApplicationBuilder AddCors( this WebApplicationBuilder builder,
- Action policyBuilder )
- {
- Throw.CheckNotNullArgument( policyBuilder );
- var props = ((IHostApplicationBuilder)builder).Properties;
- if( !props.TryGetValue( typeof( CorsPolicyBuilder ), out var currentPolicy ) )
- {
- props.Add( typeof( CorsPolicyBuilder ), policyBuilder );
- builder.Services.AddCors();
- builder.AppendApplicationBuilder( DoUseCors( props ) );
- }
- else
- {
- props[typeof( CorsPolicyBuilder )] = policyBuilder;
- }
- return builder;
+ ///
+ /// Add dangerous Cors support: this allows all orgigins, methods, headers AND supports credential.
+ /// This is unfortunately required in some testing scenario but should NEVER be used in production.
+ ///
+ /// This method, just like and
+ /// can be called multiple times: the last wins.
+ ///
+ ///
+ /// This builder.
+ /// This builder.
+ public static WebApplicationBuilder AddUnsafeAllowAllCors( this WebApplicationBuilder builder )
+ {
+ return AddCors( builder, CorsAllowAllBuilder );
+ static void CorsAllowAllBuilder( CorsPolicyBuilder o )
+ {
+ o.AllowAnyMethod().AllowCredentials().AllowAnyHeader().SetIsOriginAllowed( _ => true );
}
+ }
- ///
- /// Add Cors support for a named policy. This method can be called multiple times: the last wins.
- ///
- /// Named policy must be defined by using
- /// and configuring the .
- ///
- ///
- /// This method, just like and
- /// can be called multiple times: the last wins.
- ///
- ///
- /// This builder.
- /// The policy name.
- /// This builder.
- public static WebApplicationBuilder AddCors( this WebApplicationBuilder builder,
- string policyName )
+ ///
+ /// Add Cors support for a single policy.
+ ///
+ /// This method, just like and
+ /// can be called multiple times: the last wins.
+ ///
+ ///
+ /// This builder.
+ /// The cors policy builder.
+ ///
+ public static WebApplicationBuilder AddCors( this WebApplicationBuilder builder,
+ Action policyBuilder )
+ {
+ Throw.CheckNotNullArgument( policyBuilder );
+ var props = ((IHostApplicationBuilder)builder).Properties;
+ if( !props.TryGetValue( typeof( CorsPolicyBuilder ), out var currentPolicy ) )
{
- Throw.CheckNotNullOrWhiteSpaceArgument( policyName );
- var props = ((IHostApplicationBuilder)builder).Properties;
- if( !props.TryGetValue( typeof( CorsPolicyBuilder ), out var currentPolicy ) )
- {
- props.Add( typeof( CorsPolicyBuilder ), policyName );
- builder.Services.AddCors();
- builder.AppendApplicationBuilder( DoUseCors( props ) );
- }
- else
- {
- props[typeof( CorsPolicyBuilder )] = policyName;
- }
- return builder;
+ props.Add( typeof( CorsPolicyBuilder ), policyBuilder );
+ builder.Services.AddCors();
+ builder.AppendApplicationBuilder( DoUseCors( props ) );
}
+ else
+ {
+ props[typeof( CorsPolicyBuilder )] = policyBuilder;
+ }
+ return builder;
+
+ }
- static Action DoUseCors( IDictionary