Mp.weixin.qq.com/s/aWqiZtdpg…

First, prepare knowledge

This article discusses the technical solution of identity authentication and user authorization based on microservices architecture. It is best to be familiar with and understand the following points before reading this article:

  • Concepts related to microservices architecture: service registry, service discovery, API gateway

  • Authentication and user authorization: SSO, CAS, OAuth2, JWT

The article will attach reference links when referring to the above knowledge content.

Second, the background

As the number of enterprise application systems increases, each system can easily manage its own user data into information islands, and the decentralized user management mode hinders the evolution of enterprise applications to platforms. When the Internet business development of the enterprise to a certain scale, the construction of a unified standardized account management system is essential, because it is an important infrastructure, enterprise Internet cloud platform can bring unity for platform account management, identity authentication and user authorization ability, bring enterprises such as single sign-on (sso) across the system, the third party authorization login ability, It provides necessary conditions for building open platform and business ecosystem.

Demand analysis

Under the micro-service architecture, it is necessary to carry out reasonable business division for the platform ecosystem of the enterprise, and each business segment will become its own system, such as the official website responsible for publicity, the B2B2C mall featuring literary style, and the community-oriented property service system, etc. These systems are relatively independent and should be separated independently. Each system can also be divided according to its own business model, and an appropriate domain model can be established after overall analysis of the business model and user needs to form an independent service.

In addition, the customer scope of enterprise platform is relatively complex, including 2B businesses, 2C businesses, and 2G (goverment). Therefore, unified identity management at the platform level must involve both organizational entities and individual entities, among which organizational entities include government agencies (G), enterprise units (B), and group organizations (B). This is similar to the concept of multi-tenant architecture, but more complex than traditional multi-tenant architecture.

1) Unified Identity Manager

Unified Identity Management (UIM) is the basis of account and permission Management of the entire platform. The Unified Identity Management System (UIMS) constructed from this is called UIMS. Accounts Management, Identity authentication, user authorization, and permission control of all systems on the platform are handled by UIMS. Provides functions such as account and password management, basic information management, and role rights management. Based on the concept of unified identity governance, UIMS can be divided into three modules: two-level account system, basic authority module and basic information module. In the two-level account system, accounts are divided into organizational entity accounts and individual entity accounts. The individual entity may be subordinate to the organizational entity or not to any organizational entity, and the individual entity may be subordinate to multiple organizational entities at the same time. The basic permission module manages and authorizes the resource permissions of all business systems. The basic information module is used to describe the basic information of the organization entity and individual entity, such as the name, address, legal person, name, telephone number, gender and other basic information of the organization entity. UIMS provides a unified API for connecting subsystems.

As you can see, many systems and many services will depend on UIMS. This paper only deals with identity authentication and user authorization in UIMS, that is, two-level account system and basic permission module, according to which account service and authentication service can be independently developed or combined into one account authentication service.

For an introduction to unified Identity Management system, see https://mtide.net/ Platform – level SAAS Infrastructure – Unified Identity Management System.html

2) Software as a Service (SAAS)

An enterprise provides external IT services in two modes: private cloud deployment and public ownership service. Public cloud services, namely SAAS, provide system-level application services, including enterprise services such as enterprise email, office OA, and human resource system, and personal services such as personal email, cloud note, and cloud web disk. The platform-level SAAS application architecture is actually an upgraded version of multi-tenant architecture, which makes unified identity governance more difficult. With a two-tier account system based on UIMS, this can be easily done. It is important to note that some systems provide only personal accounts, some provide only organizational accounts, and some provide both, and the relationship between individual and organizational entities must be managed.

About the introduction of SAAS, please refer to http://www.ruanyifeng.com/blog/2017/07/iaas-paas-saas.html

3) Orginization Entity

In UIMS, an organization should be one entity, and its counterpart is a personal entity. Note that the Entity is not an Account, so to design a method for the organization Entity to log in to the controlled system, there are two options: one is to increase the organization Entity Account, the organization Entity has its own Account, can directly authenticate login; Second, the personal account belonging to the organization entity is used as the login certificate of the organization entity. Regardless of the method, UIMS should be provided with uniform and standard account credentials at the time of authentication and authorization. The specifications of the credentials are defined by UIMS. Therefore, the authentication and authorization of an organizational entity is no different from that of an individual entity.

4) Single Sign-on (SSO)

Enterprise platforms involve many subsystems. In order to simplify user management of each subsystem and improve user experience, SSO is an important goal of unified identity authentication: one login, all access. SSO is a mandatory option for enterprise internal applications, such as enterprise OA, HR, and CRM. SSO is optional for external applications. It is up to the service system to decide which application should be added to the SSO system, such as external shopping malls and property management systems. Regardless of whether or not the application adopts SSO, UIMS should technically have SSO capabilities.

Information about the SSO, please refer to https://www.cnblogs.com/EzrealLiu/p/5559255.html

5) Authorized login

With the gradual growth of the platform business, the platform will be greatly enriched by the resources based on the platform, manufacturers and customers, so an open ecosystem must be built to support the further development of the business. The platform-level authorization login function must be enabled to allow third-party applications to access. Through the authorized login of the three parties, the service capabilities of the platform will be developed to the third party, and the services and capabilities of the third party will be connected to the platform for prosperity and common development.

6) Inter-service authentication

Service systems are divided into different services. The number of services and permission requirements vary according to the granularity and service requirements. There are two types of identity authentication and authorization in the microservices architecture:

  • Authentication and authorization of internal services;

  • Authentication and authorization of external services.

Generally, internal services, such as authentication services, commodity services, and order services, are in a secure Intranet environment. When the security requirements are not high, authentication is not implemented and services trust each other.

The authentication and authorization of external services are usually initiated by external applications, which send requests to the services within the security boundary through reverse proxy or gateway. Therefore, strict authentication procedures must be implemented. Services in external applications such as wireless apps, Web servers, and desktop clients are external services.

7) Account logout and destruction

In contrast to SSO, UIMS should support one logout, all logout, SSOff (Single sign-off, non-standard term); For example, after the user logs out on the Web end, whether the wireless end APP also logs out depends on the user’s preference, but the system should provide this ability.

In addition, a unified destruction function must be provided to enable users to delete their accounts, once and all.

8) Paid license

The cloud platform should have a paid authorization mechanism to independently authorize user accounts and organizational accounts. Flexible payment model can be implemented according to the business strategy of the product:

  • Limitation: annual payment, quarterly payment, monthly payment, different limitation costs are different;

  • Function limitation: authorize different functions, the cost is different;

  • Quantity limit: maximum organization quantity limit, maximum user quantity limit, different quantity cost is different.

Iv. Technical Scheme

A) Alternative plan

Based on the concept of “unified identity governance”, the main requirements for identity authentication and authorization under the unified Identity Management System (UIMS) are presented above. At present, there are many technical means to achieve unified identity authentication and authorization, which can be summarized as the following two categories:

  1. Traditional Cookie + Session solution, stateful Session mode;

  2. Token/ticket based solution, stateless interaction mode.

Specific include:

  • Distributed Session

  • OAuth2.0

  • JWT

  • CAS

Each of the above schemes has advantages and disadvantages:

  • Distributed Session is an old and mature solution, but it is generally not adopted by microservices because of its station-oriented communication characteristics and apI-oriented stateless communication advocated by microservices, and shared storage has security risks.

  • OAuth2.0 is a mature authorized login solution in the industry. However, OA2.0 provides four authorization modes, which can adapt to a variety of scenarios. As a token-based security system, OAuth2.0 can be widely used in scenarios requiring unified identity authentication and authorization.

About OAuth2.0 introduction, please refer to http://www.ruanyifeng.com/blog/2014/05/oauth_2_0.html

  • JWT (JSON Web Token) is a concise self-contained JSON declaration specification. Due to its decentralized storage, JWT belongs to client authorization mode and is widely used for short-term authorization and single sign-on (SSO). Because JWT information is signed, it ensures the authenticity of the sender and that the information has not been tampered with or forged. However, due to its self-contained client verification feature, once issued, the token cannot be revoked. Therefore, JWT alone as a unified authentication and authorization scheme cannot meet the requirements of unified account logout and destruction, account closure and cancellation.

Information about the JWT, please refer to http://blog.leapoahead.com/2015/09/06/understanding-jwt/

  • CAS is the most mature open source single sign-on (SSO) solution, consisting of CAS Server and CAS Client. The CAS Server is a WAR package that needs to be deployed independently and is responsible for user authentication. The CAS Client processes the access requests to protected resources on the Client and redirects the access requests to the CAS Server for authentication. It is worth noting that CAS is an authentication framework, which itself defines a flexible and complete authentication process, but it is compatible with mainstream authentication and authorization protocols such as OAuth2, SAML, OpenID, etc. Therefore, CAS + OAuth2 scheme is generally adopted to realize SSO and authorized login.

Information about the CAS, please refer to https://apereo.github.io/cas/

In microservices architecture, identity authentication and user authorization are usually separated into independent authentication services. In the selection of technology, the following points should be considered:

  1. Meet SSO’s technical requirements;

  2. Meet the need for simplicity and security;

  3. Meet the requirements of openness and expansibility.

All things considered, the stateless API pattern is recommended, which OAuth2.0 can fully meet. In addition, JWT can meet all the requirements except SSOff, and it is the most convenient and light one among all solutions. It can meet the requirements of SSOff characteristics through the combination of API gateway, so JWT + API gateway is also a recommended solution.

Scenario hypothesis: Building an image-based Classification System

To understand the details of a unified authentication and authorization scheme, consider a scenario in which the team is preparing to build an image-based item identification system that allows users to upload images through an H5 application or APP, and the system analyzes and returns recognition results. It also expects to open the system to community and industry users for commercial use; Finally, third-party applications are allowed to plug their own functionality into the IBCS to enhance its capabilities.

The following is the microservice architecture diagram of the system:

In the microservice architecture, IBCS is divided into two layers: the inner layer is in the physical internal network environment, also called internal service, and the outer layer is in the physical external network environment, also called external service, which are connected through the API gateway.

  • Internal services: Authentication services, configuration services, and image identification services are internal services. Generally, internal services trust each other. However, in scenarios with high security requirements, internal services cannot trust each other.

  • External services: Desktop APP, wireless APP, H5, and third-party apps are external services. External services are divided into two types: one is a part of IBCS, such as front-end applications such as APP and H5. The other is a third-party application outside of the IBCS. The two types of authorization are different. The former generally adopts OAuth2.0 password mode, while the latter adopts client mode.

Using the article Identification System as an example, the two recommended options are described below:

Two) The best scheme: OAuth2.0

1. Four authorization modes of OAuth2.0

  • Authorization Code

  • Simplified patterns (Implicit)

  • Password mode (Resource owner Password Credentials)

  • Client credentials

The password mode is often used for authentication of external services, the client mode is often used for authentication of internal services and authorization of open platform applications, and the authorization code mode is often used for social login and SSO. Therefore, OAuth2.0 can be used as a complete unified authentication and authorization scheme.

2. Several important roles of OAuth2.0

It is important to note that these roles are relative concepts.

  • Client: refers to third-party applications. For example, you can use QQ to log in to a douban website. However, in the microservice system, Client is usually the service itself, such as the registration and login service of APP.

  • Resource Owner: Generally refers to the user. For example, when you log in to douban website through QQ, the Owner is the user. But in microservice system, the resource owner is the service provider itself;

  • Resource Server: generally refers to the Server authorized by the Resource owner to store user resources. For example, when you log in to douban website by QQ, QQ is the Resource Server. But in microservices, service providers themselves are resource servers;

  • Authorization Server: Generally, it refers to the Authorization services of service providers. For example, QQ is used to log in to douban website. Similarly, in microservices, the authentication service is the authorization server.

3. What functions does IBCS provide

1) Core functions exposed in the form of API:
interface describe body return permissions
POST /image-classify Image recognition {picture content, token} {recognition result} Controlled interface
2) Functions provided by UIMS:
Function/API describe body return permissions
POST /accounts/ Registered interface { username, password } { sign-up-result } Uncontrolled interface
POST /accounts/login Login interface { username, password } { token } Controlled interface
POST /accounts/logout Appropriate interface { token } { logout-result } Controlled interface
SignUp-Page Unified Registration Page (UI)

Uncontrolled page
Login-Page Unified Login Page (UI)

Uncontrolled page

The registered interface, signup-page, and login-page pages are uncontrolled interfaces/pages, meaning they can be accessed without authentication.

Signup-page and login-page are unified registration and Login pages provided by UIMS. When an external service initiates a registration or Login request, there are two approaches: One is to jump to the registration or login page of UIMS. After completing the operation, the user invokes the REGISTRATION and login API of UIMS to complete the request. The second is to complete the operation in its own registration and login page, and then call UIMS registration and login API with the user name and password as parameters to complete the request. It is recommended to use the first method, which is similar to the whole network pass, with unified user experience and no need to repeatedly develop the registration and login page.

3) Become a developer and acquire IBCS capability set:
  1. Step 1: Apply to become a developer. Developers are divided into individual developers and organization developers, and there are two types of real-name authentication. To become a developer is to become a registered user of the platform;

  2. Step 2: Create an application. After the platform is approved, generate AppId and AppSecret and give them to developers. Each application corresponds to a pair of AppId and AppSecret. It is worth noting that each AppID is bound to a user account, so the permissions of each AppID to obtain resources and capabilities are limited by the permissions of the user account. A typical example is the object storage service (OSS/OBS).

  3. Step 3: Obtain Access tokens. According to the OAuth2.0 specification, developers apply for tokens from IBCS using the appids and AppSecret in client_credentials mode.

  4. Step 3: Interact with the platform using an Access Token that is carried each time a controlled API is called.

4) Become a developer and create third-party apps:

In general, an open platform should be built independently, and the development platform, as a subsystem of the overall cloud platform, also depends on UIMS. On an open platform, a comprehensive interface and process should be provided to guide users through all the work of developer certification and third-party application access. In addition, in the early stage, offline application can also be adopted by the administrator manual review, manual input in the background.

On an open platform, the process and steps for creating third-party applications are the same as in the previous step, “Become a developer, get the IBCS capability set.” The difference is that the previous step is to obtain the ability of IBCS, while this step “create third-party application” is based on open platform development application, similar to wechat applets.

5) Become a developer and connect heterogeneous systems (third-party applications) to IBCS:

Developers should be allowed to plug heterogeneous systems (third-party applications) into IBCS to enhance IBCS capabilities. For example, suppose that the IBCS itself does not have the ability to recognize specialty cars, but allows access to image-based specialty car recognition applications developed by other developers.

Third-party application access belongs to the category of open platform. The access process and steps are the same as the third step, “Become a developer, acquire IBCS capability set”. The open platform provides standard API, and the third party executes according to the access specification.

4. Application scenarios of four authorization modes of OAuth2.0

scenario describe Applicable mode
User registration (External services) The user completes the registration request on the registration page provided by the APP Uncontrolled interface without authentication
User logs in (external service) and returns token The user completes the login request on the login page provided by the APP and obtains the token Password mode (Resource owner Password Credentials)
User Registration (UIMS) The user goes to the REGISTRATION page of the UIMS, completes the registration request, and hops back to the original service Uncontrolled interface without authentication
User Login (UIMS) returns a token The user goes to the UIMS login page, completes the login operation, obtains the authorization code, and then carries the authorization code to the redirection URI to obtain the token Authorization Code
Authentication of external services When the user uses the image recognition service on the APP, the APP calls the IBCS image recognition API and returns the result to the user Password mode (Resource owner Password Credentials)
Authentication of internal services The image recognition service obtains configuration information from the configuration service Client credentials, or simple HTTP Basic authentication
Developer: Get the IBCS capability set
Client credentials
Developers: Create third-party apps
Client credentials
Developers: Access third-party apps
Client credentials

5. Client and user authentication

Service authentication can be divided into:

  1. Uncontrolled services/interfaces without authentication;

  2. Client authentication (service authentication) : A client (service) must identify itself before accessing another service.

  3. Service authentication (user authentication) : When a user accesses a resource through a client (service), the user must authenticate himself or herself.

For example, after logging in to IBCS through APP, the user accesses the image recognition service: After the user logs in and obtains the token, the APP carries the token to initiate a request to the image recognition service. The image recognition service first invokes the authentication service to verify the identity of the APP (through ClientId and ClientSecret), and then verifies the identity of the user (through token). If both APP and user are authorized, the request is approved and the recognition result is returned.

6. Cross-domain problems

The same origin policy of browser delimits the security boundary of Web application and is an important basis of Web application security model. Token-based security systems face two problems under the constraint of same-origin policy:

  1. Cross-domain request;

  2. Cross-domain maintenance of SSO login status.

1) CORS scheme

The first problem is that the CORS scheme is generally adopted. The access-Control-Allow-Origin parameter can be declared in the response header of the server to solve the cross-domain request problem.

2) Same-domain SSO scheme

The second problem is that in the codomain environment, the traditional method is to adopt cookies. In a cross-domain environment, there are several solutions. For security and simplicity, this solution is recommended:

  • According to business requirements, applications are divided into SSO applications in the same domain and SSO applications in the cross domain.

  • Add the applications requiring SSO state maintenance to the same-domain SSO application, and add other applications to the cross-domain SSO application.

  • For SSO applications in the same domain, they are usually intra-enterprise applications or highly correlated applications. The domain names of these applications use the same parent domain name and continue to use the Cookie scheme.

  • For cross-domain SSO applications, SSO state retention is not provided. When the user opens the application for the first time, the server cannot perceive the user’s login status because the Cookie cannot cross domains. At this time, the user is not logged in. When the user accesses the controlled page or clicks the login page, the user must log in again.

7. Log out and close your account

OAuth2.0 is a centralized token security system that can be logged out of the system by revoking tokens. Closing accounts is similar.

8. Software licensing

You can add rule filters to the authentication service or API gateway to apply commercial authorization policies to authorization rules.

9. Technical selection

Practice will be written later, please look forward to……

Third, the second scheme: JWT + API gateway

JWT is a self-contained client-side token system specification, which is its biggest difference from OAuth2.0. Otherwise, JWT can simply be considered a semi-automatic version of the OAuth2.0 cryptographic pattern. In the implementation of JWT scheme, it is basically consistent with OAuth2.0 in most cases. This paper will not repeat the elaboration, but only explain a few key points and differences.

1. Implement token revocation with API gateway

Since JWT is a self-contained client-side token system, the token issue does not require server validation, only client-side validation. After the client validates and unsigns, it gets the necessary information, such as basic user information and permission identifiers. This design naturally has the problem of being unable to undo tokens. The solution is to intercept JWT at the API gateway. There are several ways to do this:

  1. Token revocation is issued by UIMS and notified to the gateway through message queue, API and other means. The gateway maintains a blacklist of revoked tokens and compares all JWT passing through the gateway. If TRUE, it rejects forwarding and returns 401.

  2. After token revocation is performed by UIMS, each time the gateway receives a JWT request, it queries the token database (such as Redis) to check whether the token has been revoked, and returns 401 if it has been revoked.

However, there are still two problems with this scheme:

  1. The advantages of JWT client unsigning will be lost to some extent, but compared with the traditional Cookie + Session scheme, this scheme is lighter and more in line with the style of stateless API of microservices.

  2. For issued tokens, the server’s token system has no control over them until the next request is made by the client, such as SSOff.

2. Client and user authentication

As with the OAuth2.0 scheme, clients also need to use ClientId and ClientSecret authentication.

3. Public key and key

JWT uses asymmetric encryption algorithms to sign headers and payloads.

1) Asymmetric algorithm

The important characteristic of asymmetric algorithm is that when using the key encryption, must use the public key decryption; When encrypting with a public key, you must decrypt with a key. With this feature, information is usually encrypted using a key on the server and decrypted using a public key on the client. Because the key is stored on the server, it is secure. The public key itself can be exposed and therefore stored on the client side.

2) Public key decryption

The JWT is encrypted by the server with the key and sent to the client. The client decrypts the JWT using the public key to obtain the plaintext of the JWT. JWT contains a wealth of information (usually basic user information and permission identifiers) that can be trusted by the client once decryption succeeds, so that the client does not have to rely on the server for repeated authentication.

4. Authentication between services

1) Internal service authentication

Taking IBCS as an example, when the image recognition service service with JWT requests resources from the configuration service, the configuration service uses public key decryption. As long as the decryption succeeds, the configuration service can fully trust the image recognition service, so it does not have to rely on the repeated authentication of the authentication service. HTTP Basic authentication can also be used for simple authentication in scenarios with low security requirements.

2) External service authentication

Likewise, when an external APP JWT to carry on Intranet image recognition services request, the image recognition services using public key to decrypt, as long as the decryption is successful, image recognition services can completely trust the APP, is different is that external services to network service request, must pass through the API gateway, performed by the gateway filtering rules, Ensure that JWT is still in a valid state.

5. Cross-domain problems

Consistent with OAuth2.0’s cross-domain solution.

Five, the summary

In this paper, the design scheme of unified identity authentication and authorization under microservices architecture is presented. Starting from the concept of “unified identity governance” under platform-level SAAS model, the key demand points are sorted out and corresponding solutions are proposed. OAuth2.0 is the best solution, but in practical application, should follow the “appropriate principle”, “simple principle” and “evolution principle” three principles, can not blindly copy.

6. Reference links

  1. SAAS, http://www.ruanyifeng.com/blog/2017/07/iaas-paas-saas.html

  2. SSO, https://www.cnblogs.com/EzrealLiu/p/5559255.html

  3. CAS, https://apereo.github.io/cas/

  4. UIMS, https://mtide.net/ The foundation of platform-level SAAS architecture – unified Identity Management system.html