'Handle authentication by default

Is there any way to apply an authentication filter by default on all controllers in your api in .NET Core 5? right now I have to define a scheme over every endpoint:

[Authorize(AuthenticationSchemes = "CustomDigestAuthentication")]

registration of authentication schemes looks like this:

 services.AddAuthentication("defaultScheme")
                    .AddPolicyScheme("defaultScheme", "defaultScheme", options =>
                        options.ForwardDefaultSelector = context => context.Request.IsCustomJWtAuthentication() // Extension method
                            ? SignatureAuthenticationDefaults.CustomJwtAuthenticationScheme
                            : SignatureAuthenticationDefaults.AuthenticationScheme)
                .AddCustomJwtAuthentication()
                .AddCustomDigestAuthentication();

Thanks



Solution 1:[1]

As far as I know, the asp.net core contains the default Scheme settings when you register the service.

I suggest you could try to set the default sechema like this:

Below codes is used to register services required by authentication services. It contains the defaultScheme parameter, the defaultScheme parameter specifies the name of the scheme to use by default when a specific scheme isn't requested.

I think you could just set it and avoid using the authentication filter to set the default scheme .

 services.AddAuthentication("CustomDigestAuthentication")
                    .AddPolicyScheme("defaultScheme", "defaultScheme", options =>
                        options.ForwardDefaultSelector = context => context.Request.IsCustomJWtAuthentication() // Extension method
                            ? SignatureAuthenticationDefaults.CustomJwtAuthenticationScheme
                            : SignatureAuthenticationDefaults.AuthenticationScheme)
                .AddCustomJwtAuthentication()
                .AddCustomDigestAuthentication();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Brando Zhang