banner



How Are User Claims Created When A User Registers With Identityserver4

This post contains affiliate links, which means I'll receive a committee if you buy through my links, at no extra cost to you lot. You tin always read the disclaimers for more info.

Last update is 3th May 2021

Identity Management is an essential function of whatsoever solution. In this post, I volition build an Identity Service by using IdentityServer4 and ASP.Internet Identity together.

Any modern application contains many components: front-ends, back-ends, and third-party APIs. How should you implement authentication and authorisation?

محتوى المقالة

  • 1 What Is ASP.Internet Core Identity
  • ii What Is IdentityServer4
  • 3 Edifice Identity Service
    • 3.1 1- Identity MicroService Project Startup
      • 3.1.1 Create a new ASP.NET Core Spider web Application (Empty) projection.
      • 3.ane.2 Install IdentityServer4 Templates by executing the following command:
      • 3.i.iii Add IdentityServer4 and its QuickStart UI Files along with ASP.Net Identity Nuget packages to the project by running the command:
        • 3.i.3.1 In .Internet Core two.two:
        • iii.one.3.2 In .NET Cadre 3.1
      • 3.1.4 After that, you can build the project to make sure that it'south running.
    • 3.ii ii- Configuring Identity MicroService Projection
      • 3.two.1 Define your resource and clientS
      • 3.two.2 Add IdentityServer4 and Asp.NET identity to middleware
    • iii.3 three- Configuring Web Customer Project
    • 3.four 4- Configuring Single Page Application Projection
    • iii.v 5- Configuring Test API Resources Project
  • 4 Running the solution

What Is ASP.NET Cadre Identity

ASP.NET Cadre Identity is a membership nuget bundle that can be used in whatsoever ASP.NET project Type: MVC, WebForms, WebAPI. It has the primary following capabilities:

  1. Hands customize the user profile data.
  2. Storing the users' info in a persistence data store using Entity Framework Lawmaking Offset.
  3. Unit testability
  4. Restrict admission past roles
  5. Claims-based provider

You tin can also check this ASP.NET Core Identity demo.

So ASP.NET Identity is Hallmark and Authorization provider. Why do we need IdentityServer4?

ASP.NET Identity can receive a security token from a 3rd-party login provider like Facebook, Google, Microsoft and Twitter. But If y'all desire to issue a security token for a local ASP.Internet Identity user you need to work with a third-party library like IdentityServer4, OpenIddict.

If you practice a fiddling research, you will detect IdentityServer4 is the most common.

What Is IdentityServer4

IdentityServer4 is an OpenID Connect and OAuth 2.0 Framework for ASP.NET Core. It is a nuget parcel that is used in the asp.net core middle ware to enable using the login/logout, token/authorize and other standard protocol endpoints.

Note

Every bit mentioned in IdentityServer4 documentation, IdentityServer4 with Apache-ii.0 License will be maintained with bug fixes and security updates until November 2022. If you desire to go the newer versions in the future, Duende IdentityServer is bachelor under FOSS (RPL) and commercial license. Just Development and testing volition exist free.

To have a good understanding of the architecture, I think you better review the main terminology that will be used during this mail service:

  1. User: a homo (me and you lot) that is using a client
  2. Customer: it'due south the software like web-browser, mobile app and any code that requests a resources.
  3. Resources: what you want to protect using identityserver4
  4. Access Token: it is the token that is used by a client to admission the API resource.
  5. Refresh Token: each access token has an expiry engagement. The refresh token is used to get a new admission token without the user interaction. The client should be immune to practice that by setting AllowOfflineAccess to true in client configuration in IdentityServer4.
  6. Grant Blazon: it is the type of interaction between the client and the IdentityServer. based on your client you lot should cull the suitable grant blazon.

Building Identity Service

You can see the post-obit steps in the IdentityServer4 docs for more details. The last output will be a visual studio 2019 solution that contains:

  1. IdentityMicroservice (IdentityServer4 and ASP.Cyberspace Identity)
  2. ClientsProjects\SPAClient (Single Page Awarding Client)
  3. ClientsProjects\WebClient (ASP.Cyberspace MVC Client)
  4. ApiResrouceProjects\TestApiResource (Represents a secured resource)
visual studio 2019 solution

one- Identity MicroService Projection Startup

This is the projection that is responsible for securing APIs, configuring your clients and storing users' data. You can see the source code on Github.
Here are the steps:

Create a new ASP.Internet Core Web Application (Empty) project.

create empty aspnetcore3.1

Install IdentityServer4 Templates past executing the following control:

dotnet new -i IdentityServer4.Templates

Add IdentityServer4 and its QuickStart UI Files along with ASP.NET Identity Nuget packages to the project by running the control:

dotnet new is4aspid --force
dotnet new is4aspid --force
In .Net Cadre two.2:

After running the command mentioned above, make sure to modify the project to .NET 2.ii and update the Nuget packages, because executing the command volition touch on the .csproj file and might downgrade the .net core version, based on the IdentityServer4.Templates version.

You may need to update the following Nuget packages by modifying csproj file directly:

"Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.ii.3"
"Microsoft.EntityFrameworkCore.Tools" Version="ii.two.4"
In .NET Core 3.1

After running the command mentioned in a higher place, make sure to change the project from .Cyberspace Core 3.0 to .Net Cadre 3.one and update the IdentityServer4 Nuget packages from 3.0 to 3.ane, because executing the command will bear on the .csproj file and might downgrade the .net core version based on the IdentityServer4.Templates version.

Y'all will update the following Nuget packages:

"Microsoft.EntityFrameworkCore.Tools" Version="iii.one.0"

You need to remove "Microsoft.AspNetCore.App" nuget package because information technology'due south not needed in .NET Core three.1. This will cause error in ApplicationDbContext and Startup.cs considering of missed Nuget packages and then install:

  • Microsoft.AspNetCore.Identity.EntityFrameworkCore iii.one.0
  • Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore three.ane.0

You lot will besides get a alert message for IHostingEnvironment considering this interface has a replacement in .NET Core 3.one then you should use IWebHostEnvironment.

In ConfigureServices() in startup.cs file add this:

//services.AddMvc().SetCompatibilityVersion(Microsoft.AspNetCore.Mvc.CompatibilityVersion.Version_2_1); services.AddControllersWithViews();        

In Configure() in startup.cs file, you need to change this:

app.UseRouting(); 	    // Block 4:             //  UseIdentityServer include a call to UseAuthentication             app.UseIdentityServer();             app.UseAuthorization();              //app.UseMvcWithDefaultRoute();             app.UseEndpoints(endpoints =>             {                 endpoints.MapControllerRoute(                     name: "default",                     design: "{controller=Home}/{activeness=Index}/{id?}");             });        

After that, yous tin build the project to make sure that it's running.

firstrun after successful build

2- Configuring Identity MicroService Projection

The main files yous should review and alter:

  1. Config.cs
  2. Startup.cs

Define your resources and clientS

IdentityServer4 gives two options to configure. You tin can use the InMemory Configuration or Use Database storage. In this example, we will use InMemory for the sake of brevity.

In config.cs file you volition define the API resources you want to protect and clients that the user will apply to admission its resources. this file will be used in the side by side pace add the middleware in Startup.cs

In your existent scenario project, yous need to employ the database configuration. IdentityServer4 has ready implementation for SQL Server using Entity Framework Core. In this sample, The Config.cs file will look similar the following:

// Cake 1: All APIs, I want to protect in my organization         public static IEnumerable            GetApis()         {             return new ApiResource[]             {                 new ApiResource("identity.api", "Identity API"),                 new ApiResource("test.api","Test API")             };         }          public static IEnumerable              GetClients()         {             return new[]             {                 //Block ii:  MVC client using hybrid menses                 new Client                 {                     ClientId = "webclient",                     ClientName = "Web Client",                     RequireConsent = simulated,                     AllowedGrantTypes = GrantTypes.HybridAndClientCredentials,                     ClientSecrets = { new Hole-and-corner("49C1A7E1-0C79-4A89-A3D6-A37998FB86B0".Sha256()) },                      RedirectUris = { "https://localhost:5002/signin-oidc" },                     FrontChannelLogoutUri = "https://localhost:5002/signout-oidc",                     PostLogoutRedirectUris = { "https://localhost:5002/signout-callback-oidc" },                      AllowOfflineAccess = truthful,                     AllowedScopes = { "openid", "profile", "identity.api","examination.api" }                 },                  //Block 3: SPA customer using Lawmaking period                 new Client                 {                     ClientId = "spaclient",                     ClientName = "SPA Client",                     ClientUri = "https://localhost:5003",                     RequireConsent = false,                     AllowedGrantTypes = GrantTypes.Code,                     RequirePkce = true,                     RequireClientSecret = false,                     AllowAccessTokensViaBrowser = true,                      RedirectUris =                     {                         "https://localhost:5003/index.html",                         "https://localhost:5003/callback.html"                     },                      PostLogoutRedirectUris = { "https://localhost:5003/index.html" },                     AllowedCorsOrigins = { "https://localhost:5003" },                      AllowedScopes = { "openid", "profile", "identity.api" ,"test.api" }                 }             };         }                  

Add together IdentityServer4 and Asp.Internet identity to middleware

Startup.cs grade is chosen in the run time when the app starts. Information technology has two methods. ConfigureServices() which register the services in DI container to be used in the applications. Configure() which configure the request's processing pipeline.

          public void ConfigureServices(IServiceCollection services)         {             //TODO: change UseSqlite to UseSqlServer             services.AddDbContext(options =>            options.UseSqlite(Configuration.GetConnectionString("DefaultConnection")));                                     // Block 1: Add ASP.Internet Identity             services.AddIdentity()                 .AddEntityFrameworkStores()                 .AddDefaultTokenProviders();                         // Block 2: Add together IdentityServer4 with InMemory Configuration             var builder = services.AddIdentityServer(options =>             {                 options.Events.RaiseErrorEvents = true;                 options.Events.RaiseInformationEvents = true;                 options.Events.RaiseFailureEvents = true;                 options.Events.RaiseSuccessEvents = true;             })                 .AddInMemoryIdentityResources(Config.GetIdentityResources())                 .AddInMemoryApiResources(Config.GetApis())                 .AddInMemoryClients(Config.GetClients())                 .AddAspNetIdentity(); //some code is not mentioend here for the sake of brevity             services.AddAuthentication();         }          public void Configure(IApplicationBuilder app)         {             if (Environment.EnvironmentName == "Development")             {                 app.UseDeveloperExceptionPage();                 app.UseDatabaseErrorPage();             }             else             {                 app.UseExceptionHandler("/Home/Error");             }              app.UseStaticFiles();             app.UseRouting();             // Cake 4:             //  UseIdentityServer include a call to UseAuthentication             app.UseIdentityServer();             app.UseAuthorization();              //app.UseMvcWithDefaultRoute();             app.UseEndpoints(endpoints =>             {                 endpoints.MapControllerRoute(                     name: "default",                     blueprint: "{controller=Home}/{action=Index}/{id?}");             });         }                                                            

Afterward configuring the Identity service project, let's move to API and Clients project configuration

iii- Configuring Web Client Project

web client configuration

As you see on the left side of the image higher up, you tin can configure using OpenIdConnect by providing the client data that is already stored in Identity service.

Authority is the public link of the Identity Service. The Grant type is hybrid which represents both implicit and authority code menstruum both. Information technology is recommended grant type for server-side web application and mobile native application.

four- Configuring Single Page Awarding Projection

spa client configuration

SPA is a client-side app. So we demand starting time to install OpenIdConnect javascript library then include the file in the HTML page.

The Grant Type is authorization-code with PKCE.

v- Configuring Test API Resource Project

api resources configuration

On the right side, I defined the API resource in the IdentityServer4 by a unique name and a label.

on the left side, I added the auth configuration to API resources startup class. Then I enabled the CORS to allow clients to make a phone call to the API.

In the configure() method, I used the Auth configuration and the CORS "default" configuration that I defined before. Kindly note that using authentication in the request pipeline is before using MVC.

Running the solution

First, Run the solution with multiple startup projects. You can enable that on Solution'south Properties > Common Backdrop > Startup Project

multiple projects startup
You better set the Identity Microservice project on height of the list.

When you clone the repo, you volition get launchsettings.json file for each projection. This file is commonly ignored and not included in the repo.

I included launchsettings.json to proceed using the same ports for each project that are used in config.cs file. The used ports are similar the post-obit:

  • Identity Microservice at port 5000
  • Test Api Resources at port 5001
  • Web Client at port 5002
  • SPA Client at port 5003

At present you can run the solution, you tin use the examination user information that are seeded already from SeedData.cs to the SQLite database that is used for storing users' information.

Effort the steps I mentioned in this post and tell me in a comment beneath

  • What do you think about using IdentityServer4 with ASP.Net Identity?
  • What other choices do yous use for Authentication in your application?

Source: https://feras.blog/how-to-use-asp-net-identity-and-identityserver4-in-your-solution/

Posted by: beasleypecom1994.blogspot.com

0 Response to "How Are User Claims Created When A User Registers With Identityserver4"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel