IDENTITYSERVER4 authorization server with ASP. NET Core Identity (ii)

Source: Internet
Author: User

In the IDENTITYSERVER4 authorization Server (1) using the ASP. NET Core Identity, IdentityServer4 memory data is used, which is inconvenient and flexible, and IdentityServer4 the data is saved to the database.

Add to IdentityServer4.EntityFramework

IdentityServer4There are two types of data that need to be saved in the database. The first is configuration data (resources and clients). The second is the IdentityServer operational data (token, code, and consent) that is generated when used. These stores use interface modeling, which IdentityServer4.EntityFramework provides the EF implementations of these interfaces in the NuGet package.
Add a IdentityServer4.EntityFramework Package

Modify Startup.cs

Startup.cs ConfigureServices Add and modify the following code in the method:

var connectionString = configuration.getconnectionstring ("defaultconnection"); var migrationsassembly = typeof ( Startup). GetTypeInfo (). Assembly.getname (). Name;services. Addidentityserver (). Adddevelopersigningcredential ()//. Addinmemorypersistedgrants ()//. Addinmemoryidentityresources (Config.getidentityresources ())//. Addinmemoryapiresources (Config.getapiresources ())//. Addinmemoryclients (Config.getclients ()). Addconfigurationstore (options = options. Configuredbcontext = Builder = Builder. Usemysql (connectionString, sql = SQL.        migrationsassembly (migrationsassembly)); })        . Addoperationalstore (options = options. Configuredbcontext = Builder = Builder. Usemysql (connectionString, sql = SQL.            migrationsassembly (migrationsassembly)); This enables automatic token cleanup.            This is optional. Options.  Enabletokencleanup = true;          Options.        Tokencleanupinterval = 30; })        . Addaspnetidentity<applicationuser> ();
Add migration

Open a command prompt in the project directory. Run the following two commands at the command prompt, one for identityserver configuration and the other for persistent authorization:

dotnet ef migrations add InitialIdentityServerPersistedGrantDbMigration -c PersistedGrantDbContext -o Data/Migrations/IdentityServer/PersistedGrantDbdotnet ef migrations add InitialIdentityServerConfigurationDbMigration -c ConfigurationDbContext -o Data/Migrations/IdentityServer/ConfigurationDb

Special note: When using MariaDB or MySQL database, after executing the first command, open data\migrations\identityserver\persistedgrantdb\ in VS PersistedGrantDbContextModelSnapshot.cs file, find about 32-34 lines like the following:

                    b.Property<string>("Data")                        .IsRequired()                        .HasMaxLength(50000);

HasMaxLength(50000)change the number inside to HasMaxLength(20000) , because the original length of 50000 exceeds the length of the MySQL field.
After you have modified and saved, execute the second command.
The modified content looks like this:

                    b.Property<string>("Data")                        .IsRequired()                        .HasMaxLength(20000);
Initializing the database

After you have migrated, you can write code to create the database from the migration. You can also seed the database by setting the memory configuration data that you previously defined. Startup.csadd a method in which to initialize the database:

private void Initializedatabase (Iapplicationbuilder app) {using (var Servicescope = app. Applicationservices.getservice<iservicescopefactory> (). Createscope ()) {servicescope.serviceprovider.getrequiredservice<persistedgrantdbcontext> ().        Database.migrate ();        var context = servicescope.serviceprovider.getrequiredservice<configurationdbcontext> (); Context.        Database.migrate (); if (!context. Clients.any ()) {foreach (var client in config.getclients ()) {context. Clients.add (client.            Toentity ()); } context.        SaveChanges (); } if (!context.                Identityresources.any ()) {foreach (var resource in config.getidentityresources ()) { Context. Identityresources.add (Resource.            Toentity ()); } context.        SaveChanges (); } if (!context. Apiresources.any ()) {foreach (var resource in Config.getapiresouRCEs ()) {context. Apiresources.add (Resource.            Toentity ()); } context.        SaveChanges (); }    }}

Configurecall it from the method:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory){    // this will do the initial DB population    InitializeDatabase(app);    // the rest of the code that was already here    // ...}

Run the program again, you can save the data to the database, we can open through the database client and see what is written to it:

  • InitializeDatabasemethod is not appropriate to execute every time the application is run, after populating the database, consider deleting (or commenting) the call to it.

IDENTITYSERVER4 authorization server with ASP. NET Core Identity (ii)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.