ASP. NET core application development on Ubuntu 16.04 04: IdentityServer4 authorization Server with ASP. NET Core Identity

Source: Internet
Author: User
Tags openid connectionstrings

New ASP. NET Core Identity Project

In the New ASP.NET Core Web 应用程序 window, select separately: ASP.NET Core 2.0 , Web应用程序(模型视图控制器) and个人用户账号

After the project is established, the run mode is changed to use the console instead of iisexpress to view the various debug information.

Open Launchsettings.json:

{  "profiles": {    "IdentityManagerServer": {      "commandName": "Project",      "launchBrowser": true,      "environmentVariables": {        "ASPNETCORE_ENVIRONMENT": "Development"      },      "applicationUrl": "http://localhost:5000/"    }  }}

Delete the iisexpress related content, and then change the port to 5000.
The buildwebhost in Program.cs should also add a URL:

        public static IWebHost BuildWebHost(string[] args) =>            WebHost.CreateDefaultBuilder(args)                .UseStartup<Startup>()                .UseUrls("http://*:5000")                .UseKestrel()                .Build();

Right-click on the project name and select编辑IdentityManagerServer.csproj
The project is eventually deployed Ubuntu Server , and when it is released, it is released with all of the packages required by the server, by adding the following line to the Csjproj file to accomplish this:

<PublishWithAspNetCoreTargetManifest>false</PublishWithAspNetCoreTargetManifest>

Looks like the downside:

  <PropertyGroup>    <TargetFramework>netcoreapp2.0</TargetFramework>    <PublishWithAspNetCoreTargetManifest>false</PublishWithAspNetCoreTargetManifest>    <UserSecretsId>aspnet-IdentityManagerServer-47CFE0C9-3D63-4880-B670-22AD145CF51C</UserSecretsId>  </PropertyGroup>

Without adding the line above, an error similar to the following will appear when running on Ubuntu after publishing:

Error:
An assembly specified in the Application dependencies manifest (... Deps.json) was not found:
Package: ' Microsoft.AspNetCore.Antiforgery ', version: ' 2.0.3 '
Path: ' Lib/netstandard2.0/microsoft.aspnetcore.antiforgery.dll '
This assembly is expected to is in the local runtime store as the application is published using the following target MA Nifest files:
Aspnetcore-store-2.0.8.xml

Use MariaDB/MySQLDatabase

NuGetAdd a MySql.Data.EntityFrameworkCore package in

To modify the connection string for a database
Open the appsettings.josn file and find a connection string similar to the following:

  "ConnectionStrings": {    "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-IdentityManagerServer-47CFE0C9-3D63-4880-B670-22AD145CF51C;Trusted_Connection=True;MultipleActiveResultSets=true" },

Modify it to look like this (comment out the original connection string here and add the new one):

  //"ConnectionStrings": {  //  "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-IdentityManagerServer-47CFE0C9-3D63-4880-B670-22AD145CF51C;Trusted_Connection=True;MultipleActiveResultSets=true"  //},  "ConnectionStrings": {    "DefaultConnection": "Server=127.0.0.1;Database=aspnet-IdentityManagerServer-180725;userid=root;pwd=123456;port=3306;sslmode=none;"  

If you have a cloud host or server, Server=127.0.0.1 replace the IP in the database server with the actual IP.

Creating a DbContext instance of MySQL using dependency injection

Open the file in the current project Startup.cs and locate the code in the ConfigureServices Central plains to use SQL Server's data context

     services.AddDbContext<ApplicationDbContext>(options =>         options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

Change it to use the MySQL database:

     services.AddDbContext<ApplicationDbContext>(options =>        options.UseMySQL(Configuration.GetConnectionString("DefaultConnection")));

The complete code after annotating the original statement using Usesqlserver and adding Usemysql is as follows:

     services.AddDbContext<ApplicationDbContext>(options =>        options.UseMySQL(Configuration.GetConnectionString("DefaultConnection")));     // services.AddDbContext<ApplicationDbContext>(options =>     //     options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
User's password options and other Identity options

ConfigureServices services.AddIdentity Add the following line after the statement ends:

Services. Configure<identityoptions> (options +//Password settings password settings options.    Password.requiredigit = false; The digital options are required.   Password.requiredlength = 6; Minimum password length options.  Password.requirenonalphanumeric = false; You must have a character other than a number and a letter options.  Password.requireuppercase = false; Must have a capital letter options.  Password.requirelowercase = false; Must have a lowercase letter options.        Password.requireduniquechars = 6; Lockout settings options.        Lockout.defaultlockouttimespan = Timespan.fromminutes (30); Options.        lockout.maxfailedaccessattempts = 10; Options.         Lockout.allowedfornewusers = true; User settings Options.    User.requireuniqueemail = true; }); services. Configureapplicationcookie (Options + =//Cookie settings options.        Cookie.httponly = true; Options.        Expiretimespan = Timespan.fromminutes (30); If the Loginpath isn ' t set, ASP. NET Core defaults//the path to/account/login. Options.         Loginpath = "/account/login";         If the Accessdeniedpath isn ' t set, the ASP. NET Core defaults//the path to/account/accessdenied. Options.        Accessdeniedpath = "/account/accessdenied"; Options.     SlidingExpiration = true; });

When the program debugging run, do not want to enter a particularly complex password every time, so in the above Password settings to set the various options false , such as the actual deployment, should be set as appropriate.

Installing the Identityserver NuGet package

In the NuGet add IdentityServer4.AspNetIdentity package, this package depends on IdentityServer4 , the installation IdentityServer4.AspNetIdentity of the time will be automatically IdentityServer4 loaded together:

Add a IdentiryServer4 configuration file

Create a new file in your project Configuration\Config.cs and modify it to the following:

Using identityserver4;using identityserver4.models;using system;using system.collections.generic;using System.Linq; Using System.threading.tasks;namespace identitymanagerserver.configuration{public class Config {public stat                IC ienumerable<apiresource> getapiresources () {return new list<apiresource> {                New Apiresource ("Socialnetwork", "Social Network") {userclaims = new [] {"Email"}        }            };            } public static ienumerable<client> getclients () {return new list<client> {new Client {ClientId = ' socialnetwork ', CLIENTSECR ETS = new [] {new Secret ("Secret").                    SHA256 ())}, Allowedgranttypes = Granttypes.resourceownerpasswordandclientcredentials, Allowedscopes = new [] {"Socialnetwork"}}, NEW Client {ClientId = "Mvc_code", ClientName = "MVC client", Allowedgranttypes = granttypes.hybridandclientcredentials, Requireconsent = False,//whether a user is required Click confirm to jump Clientsecrets = {new Secret ("Secret").                    SHA256 ())}, Redirecturis = {"HTTP://LOCALHOST:5002/SIGNIN-OIDC"},                    Postlogoutredirecturis = {"HTTP://LOCALHOST:5002/SIGNOUT-CALLBACK-OIDC"}, Allowedscopes = {IdentityServerConstants.StandardScopes.OpenId, Identityserverc Onstants. Standardscopes.profile, IdentityServerConstants.StandardScopes.Email, "Socia Lnetwork "}, Allowofflineaccess = True, allowaccesstokensviabrows   ER = true}         }; } public static ienumerable<identityresource> getidentityresources () {return new list<i dentityresource> {new Identityresources.openid (), New Identityresources.profi        Le (), New Identityresources.email ()}; }    }}
In Startup.csConfiguration IdentityServer

At ConfigureServices the end of the Add AddIdentityServer() -on configuration, part of the code is as follows:

            // Add application services.            services.AddTransient<IEmailSender, EmailSender>();            services.AddMvc();            // configure identity server with in-memory stores, keys, clients and scopes            services.AddIdentityServer()                .AddDeveloperSigningCredential()                .AddInMemoryPersistedGrants()                .AddInMemoryIdentityResources(Config.GetIdentityResources())                .AddInMemoryApiResources(Config.GetApiResources())                .AddInMemoryClients(Config.GetClients())                .AddAspNetIdentity<ApplicationUser>();

In the Configure replace with, the effect is the UseIdentityServer UseAuthentication following code:

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)        {            if (env.IsDevelopment())            {                app.UseBrowserLink();                app.UseDeveloperExceptionPage();                app.UseDatabaseErrorPage();            }            else            {                app.UseExceptionHandler("/Home/Error");            }            app.UseStaticFiles();            //app.UseAuthentication(); //UseIdentityServer中已经包含有此功能            app.UseIdentityServer();            app.UseMvc(routes =>            {                routes.MapRoute(                    name: "default",                    template: "{controller=Home}/{action=Index}/{id?}");            });        }
Create a user database

Since this is a new ASP.NET Identity project, you need to create a database (two methods to select one of them).
One, you can do this by running the command prompt from the project directory and running the following command:

dotnet ef database update -c ApplicationDbContext

As shown below:

Second, you can also enter the 程序包管理器控制台 following command in VS2017:

update-database  -c ApplicationDbContext
Run the program

Launch the application and click on the link "Register" to create a new user.

Get token

FireFox 浏览器install and run the RESTClient plug-in In, add an HTTP header field

The request method is: POST , the URL is:http://localhost:5000/connect/token
Edit text:

Where the value username : [email protected] and the value: the password 123456 account name and password registered for the previous step, replace with the actual registered value.

发送After you click the button, you can HTTP 响应 see the Token value returned in

ASP. NET core application development on Ubuntu 16.04 04: IdentityServer4 authorization Server with ASP. NET Core Identity

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.