preface

API streaking is absolutely not allowed, previously specifically for this shared JWT solution (WebApi streaking has risks); What about microservices? Adding authentication and authorization to each service can also solve the problem, but authentication and authorization appear redundant, repeated in doing things; IT gurus can’t stand IT. For microservices architectures, a unified certification authority is a must.

With the release of.netcore, IdentityServer4 came out, yes. A member of the Net Foundation dedicated to. NetCore out of the authentication and authorization framework, currently. Net circles are popular; Combined with the necessity of micro-service authentication and authorization, I decided to start with micro-service architecture learning and sharing.

The main learning and sharing ideas are code knocking as a guide. If you encounter relevant theoretical concepts, you should explain them in combination with code cases, instead of sorting out relevant articles solely for theoretical knowledge (mainly because you are worried that the summary is not good, which will make your partners confused, so you think that it is easier to understand by combining application cases).

The body of the

The main functions of IdentityServer4 are authentication and authorization. The main purpose is to use it to unify the protection of each microservice interface; Let’s start by understanding authentication and authorization:

  • Authorization: After user identity authentication, users are granted access to resources or a third system is granted access to their own resources. Resources may be personal information, files, data, and interfaces. OAuth2 is a popular authorization standard. For the authorization process, examples will be given later.

    In a company, if a partner is a leader, he or she will delegate some work to someone temporarily, such as signing or attending the meeting, by oral, email or message, when he or she is on a business trip or vacation. This process is called authorization. Without authorization, the signature is invalid and the meeting is not allowed at will.

  • Authentication: User identity Authentication, can be interpreted as login. The system verifies whether the identity credentials are legitimate, such as user name/password, face recognition and so on; OpenId Connect is a popular identity authentication standard protocol at present. OpenId is a decentralized online identity authentication system. OpenId Connect expands on the basis of OAuth2 to add identity authentication and related identity identification information.

    Companies with a slightly larger scale usually have their own office buildings and special security personnel to control the entry of non-company personnel. If they are company personnel, they can enter by swiping their credit cards. If non-company personnel need to register personal information to confirm their entry, this process can be understood as identity authentication. Only after verifying the information can you enter the company.

OpenID Connect and OAuth 2.0 are already packaged in IdentityServer4. Developers don’t need to re-implement the details of OpenID Connect and OAuth 2.0 out of the box.

During authorization, you can select four authorization modes based on application scenarios:

  1. Authorization Code: The most complete and relatively secure Authorization mode, suitable for applications with background, such as MVC project.
  2. Implicit: A simplified authorization code pattern that works with applications without a background, such as a front-to-back split project;
  3. Resource Owner Password Credentials: Obtain authorization through the user name and Password. These Credentials are suitable for highly trusted applications, because the user name and Password need to be entered, resulting in high security leakage risks.
  4. **Client Credentials ** : These are the no-user operation mode, suitable for machine-to-machine interconnection and applications without user intervention, such as background task scheduling applications and data collection applications.
  5. Hybrid mode: a combination of the above four.

The Credentials for the simplest Client Credentials are:

Client Credentials Client authorization mode

In client mode, there is no user, so it is simply machine-to-machine interaction. The general process is as follows:

Brief description of the process:

  1. First, the client obtains AccessToken from the authorization server with credentials that have been recorded on the authorization server in advance.
  2. The authorization server validates the client credentials and returns AccessToken directly upon success;
  3. The client accesses the resource server with AccessToken;
  4. The resource server returns the result normally. If there is no AccessToken, the protected resource cannot be accessed.

Let’s see how the code works, step by step, with the flow:

>>> First create the API project – resource server
  1. Create an OrderController and add an interface to it called Orders. The interface is not protected.

  2. The interface is not protected and can be accessed as follows:

>>> Create the authentication and authorization center project – authorization server to protect resource services

The above API interfaces are risky and need to be protected by a unified authentication and authorization center as follows:

  1. Create a new API project, introduce the IdentityServer4 package, and emulate the data in memory for easy testing;

    Explanation of terms:

    ApiScope: a scoped Token that can only access a specified range of resources;

    Client: here the Client is the application, such as MVC project, pure front-end project, Winfrom/WPF, APP, etc., must first be registered in the authorization server and get the identification and password assigned by the authorization server, then used to obtain AccessToken.

  2. When the simulation data is ready, the corresponding injection and configuration are performed in Startup, and the middleware is enabled as follows:

  3. In this way, the establishment of the authorization server is initially completed. The port monitored here is changed to 6100. Postman is used to test whether the Token can be obtained normally, as follows:

    Some novice partners may ask, how do you know which address can obtain the token? You can enter the following link in the browser to view information about the authorization server (address of the authorization server +/. Well-known/openID-configuration) :

  4. The authorization server is ready and ready to connect the resource server to the authorization server to secure the API interface (in the ApiDemo project) as follows:

    Note: ApiDemo projects need to Microsoft. AspNetCore. Authentication. JwtBearer package, because the project is based on. NetCore3.1, so the package version referenced here is 3.1.10.

  5. Then add the [Authorize] feature on the interface, protect the interface, see the running effect is as follows:

  6. To test in Postman, get the AccessToken first and then add the AccessToken to the protected API in the Header request resource server as follows:

>>> Real client access protected API– console

Create a console project with the following steps:

Here, I don’t need to explain the steps in the text. I should read the code and comment at the same time.

static async Task Main(string[] args)
{
    // 1. Create an HttpClient for the request
    var client = new HttpClient();
    // 2. Obtain information about the authorization server, which has been wrapped by IdentityModel
    var disco = await client.GetDiscoveryDocumentAsync("http://localhost:6100");
    // 3. Check whether the request is incorrect
    if (disco.IsError)
    {
        // Error prints the error message and returns it directly
        Console.WriteLine(disco.Error);
        return;
    }
    // 4. Request AccessToken to the authorization server through the identity assigned by the authorization service
    var tokenResp = await client.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest
    {
        // Specify the token address, IdentityModel, and use it directly
        Address = disco.TokenEndpoint,
        // Specify the client id assigned by the authorization server
        ClientId = "client".// Specifies the client password of the authorization server
        ClientSecret = "ordersecret"
    });
    // 5. Check whether the Token is obtained successfully
    if (tokenResp.IsError)
    {
        // If it fails, print an error message and return
        Console.WriteLine(tokenResp.Error);
        return;
    }

    // 6. Create an HttpClient that requests API resources
    var apiClient = new HttpClient();
    // 7. Set the obtained tokens in the request header as Bearer schemes
    apiClient.SetBearerToken(tokenResp.AccessToken);
    // 8. Request the protected API from the resource server
    var contentResp = await apiClient.GetAsync("http://localhost:5000/api/Order");
    // 9. Print corresponding messages
    if (contentResp.IsSuccessStatusCode)
    {
        var content = await contentResp.Content.ReadAsStringAsync();
        Console.WriteLine(JArray.Parse(content));
    }
    else
    {
        Console.WriteLine(contentResp.StatusCode);
    }

    Console.ReadLine();
}
Copy the code

This is one step away from completion, what, the resource is not protected, protected resources can be accessed normally, what step away?

In simulation for the record the client’s authorization server, isn’t it specifies the scope of access to resources, that is, the record of the client can only access authorized API resources, now get AccessToken can access all the protected resource on the server resources, it is because there is no limit to the resources in the server API resource scope, However, in actual projects, access to AccessToken is not arbitrary, which needs to be restricted. Continue to read ↓↓↓

If the scope value specified is not the same as that set when the client files in the authorization server, even if the client obtains AccessToken, it cannot access the resource normally, and error 403 will be reported.

You might be a little anxious, what is all this stuff? It’s all hard code, it’s all garbage; No, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no.

Jwt. IO: the Token generated by the client’s credentials is not the same as the Token generated by the client. The Token generated by the client’s credentials is not the same as the Token generated by the client’s credentials.

conclusion

Starting from this post, we will update learning and sharing as soon as possible. Friends will join us to study and discuss together. The next article discusses Resource Owner Password Credentials.

A handsome guy who was made stupid by the program, watch the “Code variety circle “, learn with me ~