Skip to content
This repository has been archived by the owner on Oct 22, 2024. It is now read-only.

1. .Net Core configuration

Jairo Blanco edited this page Feb 28, 2021 · 7 revisions

Configuring .NET Core applications


The tool is though to be decoupled and scalable to new implementations, respecting and extending the default functionalities of Microsoft AspNet Identity.

NuGet packages are:

  • ChustaSoft.Tools.Authorization.Abstractions: Abstractions for the project, dependencies are the ones from AspNet Identity
  • ChustaSoft.Tools.Authorization: Main package of the tool, containing services, implementations, and main configuration for the tool
  • ChustaSoft.Tools.Authorization.SqlServer: Specific implementation for SqlServer under EFCore (Could not be mandatory if other Stores are implemented)
  • ChustaSoft.Tools.Authorization.AspNet: AspNet project, thought to provide defualt endpoints and configuration for WebAPI's (not mandatory to use)

For the configuration at startup level, could be done by using two different approaches as documented below. Despite of the selected mechanims, those are the properties that the tool allows you to customize, and the default values if not indicated:

Property Type Default Value
SiteName string -
MinutesToExpire int 60
MinutesToUnlock int 15
MaxAttemptsToLock int 3
MinPasswordLength int 6
StrongSecurityPassword bool true
ConfirmationRequired bool false
DefaultCulture string en-UK
ExternalProviders IDictionary<ExternalAuthenticationProviders, ExternalAuthenticationProviderSettings> -

Using the appSettings.json section configuration

  1. Add configuration section on appsettings.json:

With that approach, it is possible to set the parameters to configure within a specific section of the appSettings.json. The values indicated here will overwrite the default values, so if no value is indicated in one parameter, it will be important to check that the values already established by default are valid for the requirements of the project that installs it.

  • By default, the configuration will look for a section called "Authorization", in case of having a section with a different name, it must be indicated as the last parameter (optional) of the configuration: authSectionName

For example:

"AuthorizationSettings": {
    "SiteName": "TestClientAPI",
    "DefaultCulture": "en-UK",
    "MinutesToExpire": 120,
    "MinPasswordLength": 8,
    "StrongSecurityPassword":  true,
    "ConfirmationRequired": true,
  },
  1. On Startup, in ConfigureServices:

services.RegisterAuthorization(_configuration, [_privateEncryptionKey_]);

  • privateEncryptionKey is the secure string that will be used for the encryption

In version 3.0, if ChustaSoft.Tools.Authorization.SqlServer package is installed, .WithSqlServerProvider([connectionString]) could be added to the same line of builder above, this will add SqlServer implementation to the project. As it will be explained above, it is possible to use the default context, migrations and services, or customize User and Role extending properties or models.

services.AddMvc().AddAuthorizationControllers();

  • This will automatically add controllers and expose the actions inside, such as:
    • login
    • register
    • confirm
    • activate
    • external-login (and callback)
  1. On Configure method again, add this line:

app.ConfigureAuthorization(env, serviceProvider, [appPolicyName]);

  • IServiceProvider should be injected in Configure method before
  • appPolicyName could be defined here

This will update automatically migrations and other required staff

Full example for Default model usage:

            //ConfigureServices
            services.RegisterAuthorization(_configuration, "d5ab5e3f5799445fb9f68d1fcdda3b9f")
                .WithSqlServerProvider("fullConnectionString");

            services.AddMvc()
                .AddAuthorizationControllers();


            //Configure
            app.ConfigureAuthorization(env, serviceProvider, "TestPolicy")
                .SetupDatabase();

Full example for Custom extended model usage:

            //ConfigureServices
            services.RegisterAuthorization<CustomUser, CustomRole>(_configuration, "d5ab5e3f5799445fb9f68d1fcdda3b9f")
                .WithUserCreatedAction<CustomUser, CustomUserAction>()
                .WithSqlServerProvider<AuthCustomContext, CustomUser, CustomRole>("fullConnectionString");

            services.AddMvc()
                .AddAuthorizationControllers();

            services.AddCors(o => o.AddPolicy("CustomPolicyName", builder =>
            {
                builder.WithOrigins("http://localhost:4200")
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .AllowCredentials();
            }));


            //Configure
            app.ConfigureAuthorization(env, serviceProvider, "CustomPolicyName")
                .SetupDatabase<AuthCustomContext, CustomUser, CustomRole>()

Using provided Settings builder

  1. With this approach, settings can be managed in a more flexible way, since they don't necessarily have to be in the appSettings.

Example of usage:

            //ConfigureServices
            services.RegisterAuthorization<CustomUser, CustomRole>("d5ab5e3f5799445fb9f68d1fcdda3b9f", x =>
            {
                x.SetSiteName("ClientApi");
                x.AddExternalProvider(ExternalAuthenticationProviders.Google, "[ClientIdParam]", "[ClientSecretParam]"); // Addking ExternalProvider
                x.SetAccountLock(5, 30); //Max Attemps | Minutes to unlock
                x.SetConfirmationRequired(true);
                x.SetDefaultCulture("es-ES");
                x.SetMinutesToExpire(4000);
                x.SetPasswordSecurity(true, 12); //Require strong security | Min number of characters
            })
            .WithSqlServerProvider<AuthCustomContext, CustomUser, CustomRole>(BuildConnectionString()); //Using SqlServer, custom context


            //Configure
            app.ConfigureAuthorization(env, serviceProvider, "CustomPolicyName")
               .SetupDatabase<AuthCustomContext, CustomUser, CustomRole>();

In case you need to add some custome options as for example OnMessageRecieve for JTWBearerEvents or other specifics needs, you can modify the behaviour using the PostConfigure options as shown in the example below:

            services.PostConfigure<JwtBearerOptions>(op =>
            {
                op.Events = new JwtBearerEvents
                {
                    OnMessageReceived = context =>
                    {
                        //Your event management goes here...

                        return Task.CompletedTask;
                    }
                };
            });

Using without AspNet tool:

Base library has a extension method to configure in any case the tool, without configuring AspNet part:

  • RegisterAuthorization<TUser, TRole>(this IServiceCollection services, IConfiguration configuration, string connectionString)
    • If generic implementation is required, typed objects should be:
      • User
      • Role
    • As AspNet package, is returning an IdentityBuilder instance, so after that, WithSqlServerProvider method can be called as explained above for adding SqlServer implementation.

Settings builder options is also provided here, so at the end, same possibilities and usage in terms of configuration than using AspNet package.

So usage at the end is s

With that approach, full Api settings in terms of security can be managed by the client app, also the flexibility for custom or default context and models is provided, services are explained in Home page

Full examples

You will be able to found full examples of integration and configuration here: