Application of IdentityServer4 in ASP (i)

Source: Internet
Author: User
Tags openid

IdentityServer4 is a set of identity authorization and access control solutions that focus on helping companies using. Net technology to build identity and access control solutions for modern applications, including single sign-on, identity management, authorization, and API security.

I'll show you how to implement OAuth authorization in. Net core, starting with the simplest licensing model, in the last detailed description of OAuth2.0, in the client-side mode, we say that it is strictly not an issue of authorization, and we look at its authorization process:

After the client requests a token from the authorization server, the authorization server returns the token directly to the client, which does not require any action by any other role, but only the interaction between the client and the authorization server. Let's take a closer look at this process with specific examples.

Operating system: Mac OS

Development tools: VS Code

Debugging Tools: Postman

Development framework:. Net Core 2.0

Before the concrete example implementation, let's talk about the plug-ins we'll use in VS code to facilitate our development, after all, vs code is not as powerful as our universe first ide-visual studio, but it's also by far the best editor, providing a variety of plugins, Almost all our development needs are met. One of the plugins we use here is called NuGet Package Manager, which allows us to manage nuget packages with shortcut keys.

Next we create a project for the authorization server, open the VS code using the console, create a WEBAPI project, use the command:

dotnet New Webapi-n Identityserver4.server

Once created, we can start to view our project and run it:

This way our project can be run successfully, we will add a reference to the IDENTITSERVER4 package below, after we install the NuGet packages Manager, we can quickly use shortcut keys, use command+p in Mac System, and then enter " >, then enter NuGet ... (Note Be sure to switch to the current project below) The following prompt appears:

Select the first option to add a package:

Press ENTER, select IdentityServer4 the latest version of the installation, here is 2.1.3, after installation, we add IdentityServer4 references in startup, and use Addidentityserver ( ) method to register the Identityserver in the dependency injection system, and of course we can wait until the configuration class is added. We first add a configuration class called Config.cs, first defining a pipeline (Scope), specifying the API resources we protect, which returns a Apiresources collection with the following code: New Apiresource ("API", " Usersapi "), the first parameter is the name of the API, and the second parameter is the name displayed:

The next step is client registration, which defines the resources that the client can return, that is, which scope definition is allowed, and the code is as follows:

Here we inject the configuration into the system,

Adddevelopersigningcredential () is an RSA certificate encryption method that generates a TEMPKEY.RSA certificate file that, when the project is started, checks to see if the certificate file exists at the root of the project and generates the file if it does not exist. Otherwise, the certificate file will continue to be used. The apiresources and clients are added to memory in turn.

The next step is to configure the IdentityServer4 pipeline, add the Configure inside the app. Useidentityserver (), where we don't use MVC, will be app. USEMVC () Comment out. Below we run our project, of course direct access to http://localhost:5000 is not to see anything, where we use a fixed address http://localhost:5000/.well-known/ Openid-configuration, you can view the configuration information of IdentityServer4 and run the following formatted content as follows:

{"Issuer": "http://localhost:5000", "Jwks_uri": "Http://localhost:5000/.well-known/openid-configuration/jwks", " Authorization_endpoint ":" Http://localhost:5000/connect/authorize "," Token_endpoint ":" Http://localhost:5000/ Connect/token "," Userinfo_endpoint ":" Http://localhost:5000/connect/userinfo "," End_session_endpoint ":"/HTTP// Localhost:5000/connect/endsession "," Check_session_iframe ":" Http://localhost:5000/connect/checksession "," Revocation_endpoint ":" Http://localhost:5000/connect/revocation "," Introspection_endpoint ":" http://localhost    : 5000/connect/introspect "," frontchannel_logout_supported ": True," frontchannel_logout_session_supported ": true, "Backchannel_logout_supported": True, "backchannel_logout_session_supported": True, "scopes_supported": ["AP        I "," offline_access "]," claims_supported ": []," grant_types_supported ": [" Authorization_code ",        "Client_credentials", "Refresh_token","Implicit"], "response_types_supported": ["Code", "token", "Id_token", "Id_token token        "," Code Id_token "," code token "," code Id_token token "," response_modes_supported ": [ "Form_post", "Query", "Fragment"], "token_endpoint_auth_methods_supported": ["client_secret_ Basic "," Client_secret_post "]," subject_types_supported ": [" public "]," id_token_signing_alg_v alues_supported ": [" RS256 "]," code_challenge_methods_supported ": [" plain "," S256 "]}
This shows that our Identityserver has been successfully configured, and we use the Postman simulation to initiate a request for a token, and we used the Token_point address: http://localhost:5000/connect/ Token get acces Token,postman configuration as follows:

The 3 parameters specified above are the parameters that the client mode needs to specify, and here is the access token we requested. Then we create an API to call our authorization server to authorize, repeat the above steps, create a WEBAPI project, no longer repeat, directly to configure the calling authorization server, this project is just an API project, do not need a full IdentityServer4 reference, Only one identityserver4.accesstokenvalidation package is allowed. In the authorization server we have occupied 5000 ports, so in this project we designated as 5001 port, in Program.cs specify 5001 port, Add. Useurls ("http://localhost:5001"):

Add a Microsoft.AspNetCore.Authorization reference to the Valuescontroller and add a [authorize] tag that requires the controller to be authorized for access.

Let's go inside the StartUp.cs to configure the licensing service:

Then we start the authorization server and API separately, we run the API, Access: Http://localhost:5001/api/values, the results are as follows:

Tip HTTP Error 401, in the status Code 401 is not authorized, we take it to postman run:

We specified the authorization mode as bearer in headers, the status 401 is not authorized, and this result is also our expected result, because we did not get the token, we continue to use the postman simulation to get access token,

We will get the Access_token into the API's headers:

Note the token and bearer in the middle of the space, and then continue to request:

So we get the value of the API to get, here we use postman to verify our results, next we create a third-party application, to request our API resources, continue to understand our authorization process, the client I use the console program to test.

We continue to use the command line to create a third-party app, named Thirdpartyapplication,identityserver4, with a NuGet package specifically designed for client applications, called IdentityModel, We still add the NuGet package by using the shortcut key, which directly follows the code, and the necessary instructions are commented directly in the code:

Using system;using system.net.http;using identitymodel;using identitymodel.client;namespace ThirdPartyApplication{ Class Program {static void Main (string[] args) {//Request authorization server Var Diso=discoveryclien T.getasync ("http://localhost:5000").            Result; if (Diso. IsError) {Console.WriteLine (Diso.            ERROR); }//The authorization server returns the token var tokenclient=new tokenclient (Diso) based on the request from the client.            Tokenendpoint, "Client", "secret"); var tokenresponse=tokenclient.requestclientcredentialsasync ("API").            Result;            if (Tokenresponse.iserror) {Console.WriteLine (tokenresponse.error);            }//If successful, the printout returns the token information else {Console.WriteLine (Tokenresponse.json);            }//Create HttpClient object var httpclient=new httpClient (); Sets the value of authorization Httpclient.setbearertoken (Tokenresponse.accesstoken); Request API Resource Var response= httpclient.getasync ("Http://localhost:5001/api/values") based on token information returned by the authorization server.            Result; If the result is returned as successful, the output API resource results if (response. Issuccessstatuscode) {Console.WriteLine (response. Content.readasstringasync ().            Result); }        }    }}

The following output results:

The above is the complete client licensing mode in our entire OAuth2.0 licensing model, the above process is simplified as follows:

Later articles will continue to explain the use of several other licensing modes. Good night, everybody.

Scan QR code Follow my public number, learn together and make progress together!

Application of IdentityServer4 in ASP (i)

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.