Spring oauth2 Development Guide (I): Architecture and development overview

Time:2022-1-9

Spring oauth2 Development Guide (I): Architecture and development overview

[TOC]

1、 Opening

The spring oauth2 development guide is a series of articles that introduce in detail the actual development of oauth2 based on spring Ecology (including spring cloud). This series will consist of five articles:

  1. (1) Overview of architecture and development: it is the beginning of a series of articles, which mainly combs and analyzes the architecture and main processes of oauth2, and makes a general and overall introduction to the current development of spring oauth2;
  2. (2) Development example of oauth2 password mode
  3. (3) Oauth2 client mode development example
  4. (4) Development example of oauth2 authorization code mode
  5. (5) Example development of oauth2 microservice scenario: Taking password mode as an example, this paper introduces the key technologies and methods of using oauth2 and integrating JWT in microservice scenario, mainly focusing on client, microservice gateway and authentication and authorization service, without involving other modules of microservice.

The first part of this series mainly focuses on the concept introduction of oauth2 system, and the other parts are biased towards actual combat. It mainly realizes three authorization modes of oauth2: password mode, client mode and authorization code mode, including displaying the interaction of several roles such as authorization server, resource server and client, as well as the integration of JWT. And each instance provides two code versions: one is based on the old spring security oauth2 component; One is based on the new spring authorization server component.

Note that the password mode is due to oauth2 1 is not recommended, so only the old component code version can be provided. For details, seehttps://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-02

If you are interested in the relevant theories of authentication and authorization platform, you can move on to my two earlier articles:

  1. The foundation of platform level SaaS architecture: unified identity management system,https://www.jianshu.com/p/990d8acfdb69
  2. Unified identity authentication and authorization under the microservice architecture,https://www.jianshu.com/p/2571f6a4e192

2、 Oauth2 architecture

At the beginning of OAuth authorization system design, it is mainly to solve the problem of third-party application login and authorization. However, due to its strict and standardized process definition, extensive authorization universality, and independent of the specific technical platform, OAuth authorization system has gradually developed into the main technical specification in the field of authentication and authorization. But in fact, the oauth2 specification is not complex. There are four main authorization modes and five roles.

Four authorization modes are:

  1. Authorization code mode
  2. Simplified mode (implicit)
  3. Resource owner password credentials
  4. Client credentials

The five main roles are:

  1. User agent / browser user agent
  2. Client client
  3. Resource owner
  4. Resource server resource server
  5. Authorization server

It is suggested to master the above concepts and clarify the relationship, which will help to have an overall understanding of the whole system. If you start with code, the resulting system must be unhealthy. It should be noted that the identity management system is an important infrastructure of any platform. Once it is not built firmly, it will inevitably plant hidden dangers, like a delay bomb buried under the foundation of the building.

Back to the topic, the four modes have their specific use scenarios, but they can also be chosen according to the actual situation during the landing process. In order to facilitate the following introduction, we assume two sets of demonstration cases: image-based classification system (IBCs) and photo album preview system (PAPS).

Why assume two sets? It is mainly to analyze and compare the applicable scenarios of various authorization modes.

Scenario a: image based classification system (IBCs)

Suppose that the team is developing a set of “image-based classification system”, which uses restful API for external interaction. Its main function is to allow users to upload pictures through H5 application or app, and return the classification results after system analysis. In order to perform the whole process of authentication, authorization, authentication and authority control of oauth2 system, we build a most simplified IBCs demonstration project:

service name category describe Technology selection
ibc-service Internal services Resource server role, image classification service Restful services developed by spring boot
idp Internal services Authorization server role, specifically responsible for authentication, authorization and authentication Spring boot development
demo-h5 External application Front end of demo application Antd Pro development
demo-service External application Back end of demo application Spring boot development

A demo application is designed here. For IBCs, the demo application is an external application and a consumer, including front-end demo-h5 and back-end demo service. However, from the perspective of the whole demonstration project, IBC service, IDP, demo-h5 and demo service are all home applications and trust each other.

It is worth noting that in the real world, there are two types of applications: one is server-side applications; The other is the application without server. The former is easy to understand. It may be an MVC single application with front and rear ends separated, or a rest front and rear end application. These are common development structures. In addition, there are some applications without or without a back-end, such as singlepage H5, a simple H5 developed by Vue or react. The whole application is only composed of JavaScript code, and the front end is the whole application. This type of application has one of the biggest security problems, that is, client_ How to store secret safely? In the server free scenario, neither the classic authorization code mode nor password mode can effectively solve this problem, because a program written entirely in JavaScript is completely transparent in essence, client_ Secret is at risk of disclosure. client_ Secret will cause the client to be forged, that is, the attacker will get the client_ ID and client_ After secret, forge an app to initiate a false request. Of course, many platforms will add redirect on the IDP side_ Uri binding or IP / domain name whitelist mechanism to effectively reduce security risks such as forgery / hijacking.

Some people say that the pkce (proof key for code exchange by OAuth public clients) protocol proposed by OAuth 2.0 specification can solve this problem. This is a wrong point of view. Pkce cannot solve the client problem in technical principle_ The risk of secret disclosure, so it is best not to use the Server-Free method when the security requirements are high. However, as an enhanced protocol, pkce can be combined with oauth2 to improve the overall security. The main process is as follows: the exposed “front end” generates a series of random verification codes, then generates a challenge code according to the verification code, and then uses the challenge code to request the authorization code from the authorization server. After saving the challenge code, the authorization server returns the authorization code to the “front end”, After the “front end” obtains the authorization code, it applies for a token from the authorization server with the random verification code + authorization code generated in the first step. After the authorization server obtains the verification code + authorization code, it generates a challenge code according to this verification code. If the generated challenge code is consistent with the challenge code saved in the next step, it will issue a license. Interested students can consult relevant materials by themselves.

Scenario B: photo album preview system (PAPS)

PAPS is a subsystem of a social platform. Similar to IBCs, it uses restful API for external interaction. Its main function is to allow users to preview their own photo albums. We build a most simplified PAPS demonstration project:

service name category describe Technology selection
photo-service Internal services Resource server role, album preview service Restful services developed by spring boot
idp Internal services Authorization server role, specifically responsible for authentication, authorization and authentication Spring boot development
demo-h5 External application Front end of demo application Antd Pro development
demo-service External application Back end of demo application Spring boot development

The only difference between the two demo cases is that the core services are different, one is image classification service, and the other is album preview service. It seems that there is no difference. In fact, their business models are very different. We will analyze this next.

Authorization code mode vs password mode vs client mode

Let’s think about how to choose authorization code mode, password mode and client mode in different business scenarios?

There are two approaches:

  1. No matter how old it is, the whole project only uses one authorization mode, which is simple and clear;
  2. Carefully analyze various business scenarios and give appropriate model selection.

The first approach is simple and rough. It seems undesirable, but it can’t be killed with a stick. It depends on the business model, design objectives and specific requirements of the project. However, only from the perspective of scientific rigor or technical research, the second method is certainly more desirable. Next, we will start with the second method to analyze the problem of mode selection in detail.

Authorization code mode and password mode

Let’s first look at the comparison between authorization code mode and password mode. As we all know, authorization code mode is the most secure mode of oauth2 system. Compared with password mode, the main difference is that there is less action for users to confirm authorization. The lack of this action leads to that users need to inform the client of their user name and password in the authorization stage, Create potential password disclosure risk. Let’s look at the comparison:

Comparison item Authorization code mode Password mode
Applicable scenario Untrusted / third party authentication and authorization, trusted / internal service authentication and authorization Trusted / internal service authentication and authorization
Development difficulty More complex Relatively simple
Security highest It is also safe as long as it is not used in untrusted / third-party scenarios

Here, the definition of trusted / internal service scenario is a relative concept, which refers to applications and services incorporated into the same set of oauth2 system, and these applications and services are developed by the same or mutually trusted teams, which can also be called first-party applications. For example, the B2C mall system under the micro service architecture basically consists of front-end H5, wireless app, API gateway, authentication and authorization service, order service, commodity service, etc. since all the above components belong to the same oauth2 system and are developed by the same team, they all belong to the trusted / internal service scenario.

So why is it a relative concept? We focus on the whole mall system. There is no doubt that the gateway belongs to the security boundary. The authentication and authorization services, order services and commodity services within the gateway belong to internal services, while the front-end H5 and wireless app belong to external applications. If these external applications are developed by other teams, we can also define them as third-party applications. In this way, with the gateway as the boundary, internal services and external services are divided, which is the so-called relative concept.

So, what is the difference between the authorization code mode and the password mode used by the front-end H5 and wireless app of the e-commerce system in the authentication and authorization stage? The authorization code mode has a layer of actions for users to confirm authorization, so as to avoid disclosing user names and passwords to third-party applications. In addition, they almost provide the same security process. Isn’t the third-party application referred to here the front-end H5 and wireless app? They are self-developed applications, which are naturally credible, so there is no need to worry about the risk of leakage.

From this point of view, under the limitation of the above conditions, the security of the two modes is leveled. Follow the “simplification principle” and adopt the password mode. Of course, it is also possible for students who like to challenge complex students to choose the authorization code mode.

However, it does not mean that the authorization code mode can be replaced by the password mode. The main application scenario of the authorization code mode is the login and authorization of third-party / untrusted applications. It mainly solves the problem of how to safely authorize an application to provide user resources to another application without disclosing the user password. For example, The scenario where a third-party application (client) needs to obtain the user data (resources) of the user (resource owner) on another untrusted application (resource server) is particularly suitable for using the authorization code mode.

To sum up, the choice of authorization code mode or password mode should be determined according to the business scenario. The key decision point is whether applications or services trust each other.

Client mode

What authorization mode should be adopted for the demonstration case of PAPS album preview system?

Before answering this question, let’s think about a question: what is the object referred to by the resource owner in PAPS?

First of all, we should clarify what the resource is. Secondly, the resource is protected. Finally, whoever owns the resource is the resource owner. In PAPS, it is obvious that the protected resource is the user’s photo album, and the resource owner is the user himself.

After clarifying the meaning of the resource owner, according to the previous analysis, there is no doubt that if the demo application of PAPS is an untrusted application of a third party, the authorization code mode should be adopted; If it is a first-party trusted application, you can use the password mode. Of course, you can also use the authorization code mode without trouble.

Next, let’s analyze the model of IBCs image classification system demonstration case.

Similarly, before answering this question, let’s think again: what is the object referred to by the resource owner in IBCs?

First, the object referred to by the resource owner is not immutable. In the IBCs demo case, the demo application sends a picture to the IBC service and wants to return the classification results. What are the protected resources? Unlike PAPS album preview service, which has the concept of entity resource, its protected resource is the user’s album, while IBCs is difficult to abstract an entity resource.

It can be understood that the core capability provided by IBCs is the image classification algorithm, which is its protected resource. Obviously, the owner of the image classification algorithm is the entity organization or individual holding the algorithm, so the resource owner is the entity organization or individual. Then the contradiction comes. Take the password mode as an example. According to the design of oauth2, the resource owner provides the user name and password to the client, and the client will_ ID and client_ Secret, together with the user name and password, applies for a token from the authorization server. The resource owner here is an ordinary user of IBCs. However, as just mentioned, the resource owner should be an entity organization or individual holding the image classification algorithm. Isn’t this a contradiction?

Therefore, from the perspective of resource owner, IBCs demonstration case is not suitable for authorization code mode or password mode, and the client mode is the best choice. IBCs does not have user’s resources. Authorization code mode and password mode need user’s authorization to run. However, the resources or services provided by IBCs do not belong to users. Therefore, legally speaking, user’s authorization is not required. The analysis services provided by IBCs are irrelevant to users.

The above is an analysis model of which authorization mode to choose, starting from the dimension of resource owner. To sum up:

case scene Fit mode
IBCs image classification system case Trusted / internal services Client mode
IBCs image classification system case Untrusted / external applications Client mode
PAPS album preview system case Trusted / internal services Password mode
PAPS album preview system case Untrusted / external applications Authorization code mode

In fact, the specific reference of resource owner is not an important aspect for actual development. The key is that developers should have their own understanding and be able to use it flexibly. As an aside, although oauth2 is the authority in today’s field, we should not blindly and unconditionally believe in authority. There must be loopholes and imperfections in technological development.

Typical architecture levels and main processes of password mode

Taking PAPS album preview system as an example, we introduce the architecture level and main process of password mode.

Spring oauth2 Development Guide (I): Architecture and development overview

Typical architecture hierarchy of oauth2 password mode

As shown in the figure, it is the simplest architecture level of password mode, which can be extended as a basis in actual development. The password mode involves five main roles, in addition to a user agent / browser role:

  1. User agent / Browser: generally, single applications are MVC structures with front and rear ends separated. From this point of view, the user agent / browser can be understood as the front-end H5 application or wireless app. In other words, H5 / APP carries the user’s interactive operation and becomes the user agent. The paps demonstration case is demo-h5;
  2. Client: specifically refers to the back-end service of a single application. The paps demonstration case is demo service;
  3. Authorization server: specifically refers to the IDP (identify provider) responsible for authentication, authorization and authentication. It is also the core service of oauth2 system, which can also be simply called auth service. The paps demonstration case is IDP;
  4. Protected resources: resource servers, which are generally internal services, such as product services, order services, etc. The paps demonstration case is photo service;
  5. Resource owner: as the name suggests, that is, the owner of protected resources. Generally, it refers to the user himself. The paps demonstration case is the user.

The whole process is divided into two stages:

  • Phase I: authentication and authorization phase
  1. The user agent (demo-h5) sends the user name and password entered by the user to the client (Demo service);
  2. The demo service will the user name and password entered by the user, together with the client_ id + client_ Secret (allocated by IDP) is sent to IDP together to request token. If IDP has agreed on scope, it also needs to bring the scope parameter;
  3. IDP first validates the client_ id + client_ The validity of secret, and then check whether the scope is correct. Finally, verify whether the user name and password are correct. If they are correct, a token is generated. This step is also called “certification”;
  4. IDP returns the authentication result to the client. If the authentication passes, it returns a token. If the authentication fails, it returns 401. If the authentication is successful, this step is also called “authorization”;
  5. After receiving the token, the client performs temporary storage and creates the corresponding session;
  6. The client issues cookies to the user agent / browser.

At this point, the authentication and authorization phase is completed. There are other session schemes in steps 5-6. For example, rest applications may store tokens in the browser, but the session / cookie scheme is undoubtedly the safest choice.

In general web applications, this stage can be regarded as a user login process.

  • Phase 2: request resources after authorization
  1. The user accesses the “my album” page through the user agent (demo-h5), and the user agent initiates a request to the client (Demo service) with a cookie;
  2. The client finds the corresponding token through the session and sends a request to the photo service with this token;
  3. The photo service requests IDP to verify the validity of the token;
  4. IDP verifies the validity of the token, then judges whether the demo service has the permission to call this API according to the scope, and finally returns the verification result to the resource server. This step is also called “authentication”;
  5. The resource server determines whether to return user album data to the client according to the IDP test results (true / false or other equivalent means). If the token verification fails, 401 is returned to the client; if the scope check fails, 403 is returned. This step is also called “permission control”.

At this point, the post authorization request resource phase is completed.

In fact, the scope parameter is not the core content. In practice, it can even be ignored in order to simplify the development steps. The scope parameter is used to restrict the permissions of the client, which is different from the user permissions. For example, you can use the scope parameter in IDP to restrict a client to only initiate read (get) requests, or call several specified APIs. The specific business logic can be written by itself.

Microservice architecture level and main process of cryptographic mode

We still take the paps photo album preview system as an example to introduce the architecture level and main process of password mode in the micro service scenario.

Spring oauth2 Development Guide (I): Architecture and development overview

Oauth2 cryptographic mode microservice architecture hierarchy

In the microservice scenario, a gateway is added. The gateway is actually a reverse proxy that forwards users’ requests to the internal server. Similarly, the microservice scenario is also divided into two stages, and there is no change in the first stage. The main difference is in the second stage:

  1. The user accesses the “my album” page through the user agent (demo-h5), and the user agent initiates a request to the client (Demo service) with a cookie;
  2. The client finds the corresponding token through the session and sends a request to the photo service to the gateway with this token;
  3. The gateway intercepts the token and requests verification from IDP together with the details of this request;
  4. IDP verifies the validity of the token, then judges whether the demo service has the permission to call this API according to the scope and request details, and finally returns the verification result to the gateway. If all the checks pass, IDP generates JWT and returns it to the gateway; If the token verification fails, 401 is returned; If the scope check fails, 403 is returned;
  5. If the verification passes, the gateway will get the JWT and carry the JWT to forward the request to the resource server;
  6. The resource server parses the JWT to get the user information, queries the user album data and returns it to the gateway;
  7. The gateway returns the user album data to the client.

There are two major changes in this process: first, joining the gateway makes the whole process more complicated; Second, JWT is used as a token within the gateway. This article will not repeat the interpretation of these two points. Interested students can refer to my earlier article unified identity authentication and authorization under micro service architecture.

It should be noted that in steps 9-11, there is another processing method, that is, the scope client permission check is placed in the gateway:

  1. The gateway intercepts the token and requests verification from IDP;
  2. IDP verifies the validity of the token. After verification, query the user information and scope according to the token, generate a JWT and return it to the gateway; If not, 401 is returned;
  3. After the gateway obtains the JWT, it judges whether the client has the permission to call this API according to the scope. If so, it carries the JWT forward request to the resource server, otherwise it returns 403 to the client.

If the client permission check is placed in the gateway, the gateway should maintain the logic of scope and client permission.

Microservice architecture level and main process of client mode

Taking IBCs image classification system as an example, we introduce the architecture level and main process of client mode in microservice scenario.

Spring oauth2 Development Guide (I): Architecture and development overview

Oauth2 client mode microservice architecture hierarchy

It can be seen that the client mode process is relatively simple. The specific process will not be described here, but please note step 2:

  1. Before applying for a token from IDP, the client should first check whether a valid token is cached. If yes, it should directly skip to step 6 to initiate a service access request.

Micro service architecture level and main process of authorization code mode

We still take the paps photo album preview system as an example to introduce the architecture level and main process of authorization code mode in the micro service scenario.

Spring oauth2 Development Guide (I): Architecture and development overview

Oauth2 authorization code mode micro service architecture level

The whole process is divided into two stages:

  • Phase I: authentication and authorization phase
  1. The user clicks the login button at the user agent (demo-h5) or requests authorization to log in. This operation will access a URI of the client;
  2. The client (Demo service) directs the user to the authentication and authorization page provided by IDP, and carries the client in the ULR parameter of the page_ id,response_ type=code,redirect_ Uri (optional), scope (optional), state (optional);
  3. Through the user agent (demo-h5), the user selects whether to grant authorization on the authentication and authorization page of IDP. If the user does not log in, he needs to log in first and then operate;
  4. The user is authorized, and IDP directs the user to redirect_ URI, and attach the authorization code; If redirect is not specified_ URI, then it will be directed to the URI when the request is initiated, and the authorization code (code) will be attached;
  5. After receiving the authorization code, the client sends a token application to IDP and attaches the client_ ID (required) + client_ Secret (required) + state (if any) + scope (if any). Note that this step is initiated by the client in the background and cannot be perceived at the user level;
  6. IDP checks the client first after receiving the request_ id + client_ Whether the secret + scope (if any) is correct, then verify the authorization code, and issue a token to the client after all are correct.
  • Phase 2: request resources after authorization

The process of this stage is consistent with the micro service scenario process in password mode, which will not be repeated here.

For rest demo applications

If the demo application is a rest application, you can also handle it in steps 1 and 2:

  1. After the user clicks the login button or requests authorization login button at the user agent (demo-h5), the client (Demo service) will be notified. After receiving the notification, the client will return the redirection instruction, scope (optional), state (optional), etc;
  2. After demo-h5 receives the response, it directly directs the user to the authentication and authorization page provided by IDP, and carries the parameters returned by the client in the page URL parameters (except the state parameter, other parameters can be written in demo-h5) client_ id,response_ type=code,redirect_ Uri (required), scope (optional), state (optional), where redirect_ The URI recommendation is required and must be the URI (callback address) provided by the client.

You can also do this:

  1. After clicking the login button or request authorization login button at the user agent (demo-h5), the user will directly direct the user to the authentication and authorization page provided by IDP, and carry the client in the page URL parameter_ id,response_ type=code,redirect_ Uri (required) and scope (optional), but the state parameter does not need to be carried, because the client does not know the existence of this parameter, including redirect_ The URI recommendation is required and must be the URI (callback address) provided by the client.

So far, the whole process of authentication and authorization in authorization code mode has been completed.

Discussion: when the client first directs users to the authentication and authorization page provided by IDP, does IDP need to verify the identity of the client? Or do you need to provide a client_ What about secret?

Load problem of microservice gateway

In the microservice scenario, a large number of requests and responses are forwarded through the gateway. Let’s imagine that if, like the paps photo album system, image data is returned, and technologies such as CDN distribution network or file storage service are not adopted, the image stream is returned to users through the gateway. Will the load of the gateway be very huge?

Of course, the gateway itself can do load balancing, cache can be introduced, and data streams can be processed by CDN. These are very good high-performance schemes. In addition, is there any other way?

This paper introduces a concept in the field of network technology – load balancing. There are three modes: reverse proxy, transparent transmission mode and triangular mode. Here is a brief introduction to the triangle mode:

Suppose a network structure, including a web server, a PC client, and a load balancer. The PC initiates access to the web server through the load balancer. The access process in triangle mode is as follows:

  1. The PC initiates an access request to the web server to the load balancer;
  2. The load balancer forwards the request of the PC to the web server;
  3. After receiving the request, the web server directly sends the response data to the PC.

PC, web server and load balancer are triangular, so they are called triangular mode. The advantage of this mode is that the load balancer is only responsible for forwarding requests, while the response packets do not need to be received and forwarded, so the chief officer can reduce the data flow pressure of the load balancer itself. The triangle mode is also similar to the Dr mode of LVS. The LVS scheduler is only responsible for receiving and forwarding requests, and the real packets returned by the back-end cluster server will be sent directly to the requesting client.

According to this idea, we can introduce the triangular mode into the gateway, so that the chief officer can reduce the load pressure of the gateway.

Reuse of tokens

Let’s imagine a scenario. The platform developed by the team includes both IBCs image classification service and PAPS photo album preview service. After logging in to the platform (authenticated and authorized in password mode), the user first accesses “my photo album”, and then selects a photo from it to initiate an item identification request.

According to the mode selection analysis of the article, IBCs service should adopt client mode and PAPS service should adopt password mode. Should the client apply for two sets of tokens?

To answer this question, we still need to analyze from the specific scenario:

  1. If users need to log in to the platform before they can use IBCs and PAPS services, they only need to use a token in password mode;
  2. If the paps function can be used by tourists without login, the password mode and client mode should be handled separately.

The authorization code mode is the most stringent, followed by the password mode, and the client mode is the worst. Therefore, generally, the token of the authorization code mode can be used for other modes, the token of the password mode can be used for the client mode, and the client mode can only be used by itself.

3、 Overview of spring family oauth2 related components

Well, from this section, we get rid of the boring theoretical links and enter the same boring practical development channel.

At present, there are three ways to build oauth2 authorization system: one is based on mainstream open source components; Second, access to third-party authorization services (such as Google, GitHub oauth2); Third, develop relevant authorized components according to oauth2 standards and specifications.

Common open source components include RedHat keyloak, spring security, spring security oauth2, and the fledgling spring authorization server. It is worth mentioning that RedHat keyloak is an open source and mature Iam solution with powerful functions and can be deployed privately.

In the development ecology of spring, it is recommended to adopt the open source component scheme in the direction of spring security, which has good scalability, strong customization, wide users and active community.

Spring security oauth2 has stopped updating and is officially not recommended for further use. Related functions have been migrated to spring security, but the authorization server function is not included. The authorization server function will be provided by the spring authorization server open source component developed by the spring security team. For details, please see the official announcement:https://spring.io/blog/2020/04/15/announcing-the-spring-authorization-server

The spring authorization server project is still in iteration. The development plan of the project is hosted on zenhub. Interested students can learn by themselves:https://app.zenhub.com/workspaces/authorization-server-5e8f3182b5e8f5841bfc4902/board?repos=248032165

1) Based on Spring Framework

  • spring-security

Core component. At present, almost all spring oauth2 open source technical solutions rely on it. Core module: Spring security core.

<dependencies>
    <!-- ... other dependency elements ... -->
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-web</artifactId>
        <version>5.5.1</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-config</artifactId>
        <version>5.5.1</version>
    </dependency>
</dependencies>
  • [update stopped] spring-security-oauth2

It depends on spring security. This component has been incorporated into spring security and is officially not recommended. Previously, it was the only widely used component officially maintained by the spring security team.

<!-- https://mvnrepository.com/artifact/org.springframework.security.oauth/spring-security-oauth2 -->
<dependency>
    <groupId>org.springframework.security.oauth</groupId>
    <artifactId>spring-security-oauth2</artifactId>
    <version>2.5.1.RELEASE</version>
</dependency>
  • spring-security-oauth2-authorization-server

It depends on spring security. After spring security officially announced that it would stop updating the spring-security-oauth2 component, it launched a replacement component of the authorization server. After integrating spring-security-oauth2, spring security does not include the authorization server function. Therefore, if this function needs to be developed, it should be used together with spring-security-oauth2-authorization server.

<!-- https://mvnrepository.com/artifact/org.springframework.security.experimental/spring-security-oauth2-authorization-server -->
<dependency>
    <groupId>org.springframework.security.experimental</groupId>
    <artifactId>spring-security-oauth2-authorization-server</artifactId>
    <version>0.1.2</version>
</dependency>

2) Based on spring boot

  • spring-boot-starter-security

It depends on spring security. Equivalent to spring boot + spring security, including securityautoconfiguration by default Class, so some automatic configuration will be performed, which can simplify the development steps. If you want to turn off automatic configuration, you can modify the spring boot startup annotation to @ springbootapplication (exclude = {securityautoconfiguration. Class})

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

3) Based on spring cloud

  • spring-cloud-starter-oauth2

It relies on spring-boot-starter-security + spring-security-oauth2 and provides many additional function implementations, which is more practical in the microservice scenario.

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>Hoxton.SR12</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>
    
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-oauth2</artifactId>
</dependency>

3、 Core component selection

Best solution: spring boot starter Security + spring authorization server

Spring-security-oauth2 has been migrated to spring security, and spring boot starter security integrates spring security and makes many simplified configurations, which is especially suitable for building spring boot programs. As of August 2021, the latest version of spring authorization server is 0.1.2. Please pay attention to the official newshttps://spring.io/blog/2020/04/15/announcing-the-spring-authorization-server

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

<!-- https://mvnrepository.com/artifact/org.springframework.security.experimental/spring-security-oauth2-authorization-server -->
<dependency>
    <groupId>org.springframework.security.experimental</groupId>
    <artifactId>spring-security-oauth2-authorization-server</artifactId>
    <version>0.1.2</version>
</dependency>

The spring authorization server project complies with oauth2 1 specification and does not support password mode, so the project using this mode can consider alternatives.

https://app.zenhub.com/workspaces/authorization-server-5e8f3182b5e8f5841bfc4902/issues/spring-projects/spring-authorization-server/459

Spring oauth2 Development Guide (I): Architecture and development overview

Screenshot of official reply in password mode not supported by spring authorization server

Alternative: spring-security-oauth2 or spring-cloud-starter-oauth2

This scheme adopts spring-security-oauth2, which has been officially stopped by sprnig security, so it is no longer recommended. Also note spring-security-oauth2 2.4.0 Release and later versions will prompt deprecated.

  • If spring-security-oauth2 is used, POM references are as follows:
<!-- https://mvnrepository.com/artifact/org.springframework.security.oauth/spring-security-oauth2 -->
<dependency>
    <groupId>org.springframework.security.oauth</groupId>
    <artifactId>spring-security-oauth2</artifactId>
    <version>2.3.8.RELEASE</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.springframework.security.oauth.boot/spring-security-oauth2-autoconfigure -->
<dependency>
    <groupId>org.springframework.security.oauth.boot</groupId>
    <artifactId>spring-security-oauth2-autoconfigure</artifactId>
    <version>2.1.2.RELEASE</version>
</dependency>

<!--  spring-security-oauth2-autoconfigure 2.1.3. Release and later versions will prompt deprecated.
  • Or spring-cloud-starter-oauth2, POM references are as follows:

Spring cloud starter oauth2 integrates spring security oauth2 and makes many simplified configurations. It is one of the main schemes to build oauth2 based on open source software for a long time.

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-oauth2</artifactId>
</dependency>