Single sign-on (SSO) is a popular login method for multi-domain enterprise sites. In this paper, with the help of real life scenarios, we strive to thoroughly clarify the principle and process of OAuth2.0 single sign-on. At the same time, the realization scheme of permission control and its application in microservice architecture are summarized.

1 What is single sign-on

1.1 Multi-Point Login

In the traditional multi-point login system, each site has realized the account database and login module for this site. The login status of each site is not recognized. You need to log in to each site manually. As shown below, there are two terms with the following meanings:

  • Authentication: Authenticates the user’s identity.
  • Authorization: Verifies user access rights.

1.2 Single sign-on

Single sign-on (SSO) Multiple sites (192.168.1.20x) share one authentication and authorization server (192.168.1.110 is shared by the user database and the authentication and authorization module). Once a user logs in from one of these sites (for example, 192.168.1.201), he or she can access all the other sites without having to log in. Furthermore, sites can interact directly with each other through this login status.

2 OAuth2 Authentication and authorization process

2.1 Life Examples 【★★ Key ★★】

To intuitively understand the OAuth2.0 process, let’s assume a life scenario like this:

(1) Archives Office A(Client/Client) : marked with the ID and password of the Archives Office, is the organization that controls archive resources. There are also many archives B/C/… , each archives office stores different archives (resources/resources), such as political, economic, military, cultural, etc.;

(2) Citizen Zhang SAN (Resource Owner/Resource Owner) : identified by “user name/password”, needs to check the archives in each archives bureau;

(3) Police station (authorization Server/Authentication Server) : can be a single huge police station, or can be a data sharing police station cluster, in charge of the information, provide external interface functions:

  • Records Bureau information: The “Records Bureau ID/ password” of all records bureaus to prove the identity of the records Bureau;
  • Citizen information: “user name/password” of all citizens, and can provide the Authentication of the user.
  • Citizen’s authority to the archives bureau: there is a mapping table of citizen’s authority to the archives bureau, which can check whether each citizen has the operation authority (Authorization/Authorization) to each archives bureau. Usually, a layer of official posts (roles) will be added to the design. Which official posts (roles) each citizen belongs to and which official posts (roles) have operational authority over a particular archives bureau.

2.1.1 Zhang SAN visited Archives Bureau A for the first time

Zhang SAN has never visited the archives bureau before, this is the first time to come to the archives Bureau. Understand according to the serial number below:

(1) Zhang SAN comes to the “archives office” of “Archives Bureau A”, which requires real-name registration before inquiry, and is directed to the “User Registry office” for handling (HTTP redirect);

(2) Zhang SAN went to the “user registry” of “Archives Bureau A”, but he could neither prove his identity (authentication) nor prove his authority (authorization) to check file A. Zhang SAN carries the client-ID of Archives Bureau A and is redirected to the “Authorization letter issuing Office”.

(3) Zhang SAN came to the “Authorization letter Issuing office” of the “police Station” and showed the logo of Archives Bureau A, hoping to issue an authorization letter (authorization). It requires proof of identity (authentication) first, which is redirected to the “User Authentication Office”;

(4) Zhang SAN comes to the “User Identity Verification Office” of the “police station” and gets the user identity Form (web login Form);

(5) Zhang SAN fills in his user name and password and submits it to the “User Identity Verification Office”, which checks the user name and password match from the private database to determine that the person is Zhang SAN, issues an identity certificate letter and completes the authentication. John was redirected to the “Authorization letter issuing Office” with his identification letter and the logo of Archives Bureau A.

(6) Zhang SAN came to the “Authorization letter issuing office” again, showed his identification letter and the logo of Archives Bureau A. The office found from the private database that Zhang SAN’s official position was at the level of mayor (role), and the official position had the inquiry authority of archives Bureau A. So he issued an authorization letter (authorization code/code) of “Allowing Zhang SAN to inquire archives Bureau A”. Zhang SAN with authorization letter is redirected to “archives bureau” “user login office”;

(7) Zhang SAN went to the “User Login Office” of the “Archives Bureau”, which privately took out the client-ID and password of the Archives Bureau A, attached with the authorization letter (code) zhang SAN showed, and applied for the “Token” for Zhang SAN at the “Waist License Issuing Office” of the “police Station”. In the future, Zhang SAN could show his identity and authority with this waist license. Redirected to “archives”;

(8) The Session of Zhang SAN has been associated with the token, so you can check the file directly through the “file Office”.

2.1.2 Zhang SAN visits Archives Bureau B for the first time

John has successfully visited archives bureau A. Now he is going to visit archives Bureau B. Understand according to the serial number below:

(1)/(2) the same as above;

(3) Zhang SAN has already got the “Identification letter” and directly issued the “Authorization Letter issuing Office” of the “Police Station” for “visiting archives Bureau B”;

(4) (5)/(6);

(7) The “User Registry” of “Archives Bureau B” completes registration;

(8) Files found in “Archives Office” of “Archives Bureau B”.

2.1.3 Zhang SAN visits Archives Bureau A again

Zhang SAN has successfully visited archives bureau A. Now he will visit archives Bureau A. Understand according to the serial number below:

(1) Directly and successfully check the archives;

(2~8) no.

2.2 PRINCIPLES of HTTP Redirection

In HTTP, the server sends a REQUEST from the browser to the server. If the server finds that the REQUEST is not under its jurisdiction, it sends you to a URI on its own server or another host. As we go to the government department, every time we go to A window, the staff will say, “You bring material A, go to the X window of the institute, or other Y Windows Z” for the next procedure.

2.3 SSO workflow

At this point, it is easy to understand the OAuth 2.0 authentication/authorization process, which will not be described here. Please refer to the “2.1 Life Examples” section to understand.

2.4 OAuth2.0 advanced

  • Tools.ietf.org/html/rfc674…
  • Tools.ietf.org/html/rfc675…
  • Blog.csdn.net/seccloud/ar…

According to official standards, OAuth 2.0 shares four licensing modes:

  • Authorization Code: it is used between server-side applications, which is the most complex and the mode adopted in this paper.
  • Implicit: used in mobile apps or Web apps (these apps are used on the user’s device, such as raising wechat on the phone for authentication and authorization)
  • Resource Owner Password Credentials: Applications are directly trusted (they are all developed by the same company and used in this example)
  • Client Credentials: Used for application API access.

3 Implement authentication and authorization based on SpringBoot

3.1 Authorization Server

(1) pom.xml

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

Copy the code

(2) application.properties

Server. port=8110 ## Listening portCopy the code

(3) AuthorizationServerApplication.java

@ EnableResourceServer / / resource server public class AuthorizationServerApplication {/ /... }Copy the code

(4) Configure the authorization service parameters

@Configuration @EnableAuthorizationServer public class Oauth2AuthorizationServerConfigurer extends AuthorizationServerConfigurerAdapter { @Override public void configure(final ClientDetailsServiceConfigurer clients) Throws Exception {client.inmemory ().withClient(" webApp ").secret("secret") // Client ID /secret .authorizedGrantTypes("authorization code").scopes("user_info").autoapprove (true) // Automatically approve .accessTokenValiditySeconds(3600); / / valid for 1 hour}} @ Configuration public class Oauth2WebSecurityConfigurer extends WebSecurityConfigurerAdapter {@ Override protected void configure(HttpSecurity http) throws Exception { http.requestMatchers() .antMatchers("/login", "/oauth/authorize/oauth/logout") .and().authorizeRequests().anyRequest().authenticated() .and().formLogin().permitAll();  } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication().withUser("admin").password("admin123").roles("ADMIN"); }}Copy the code

3.2 Client (Service Website)

(1) pom.xml

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

Copy the code

(2) application.properties

server port=8080
security.oauth2.client.client-id=webapp
security.oauth2.client.client-secret=secret
security.oauth2.client.access-token-uri=http://localhost:8110/oauth/token
security.oauth2.client.user-authorization-uri=http://localhost:8110/oauth/authorize
security.oauth2.resource.user-info-uri=http://localhost:8110/oauth/user

Copy the code

(3) Configure WEB security

@Configuration @EnableOAuth2Sso public class Oauth2WebsecurityConfigurer extends WebSecurityConfigurerAdapter { @Override public void configure(HttpSecurity http) throws Exception { http.antMatcher("/**").authorizeRequests() .antMatchers("/", "/login").permitAll() .anyRequest().authenticated(); } } @RestController public class Oauth2ClientController { @GetMapping("/") public ModelAndView index() { return new ModelAndView("index"); } @GetMapping("/welcome") public ModelAndView welcome() { return new ModelAndView("welcome"); }}Copy the code

3.3 User Rights Control (Role-Based)

  • On the authorization server, define roles for each user: user= user, admin= admin/user, root= root/admin/user
  • In a business web site (client), annotations indicate which roles are available
@RestController public class Oauth2ClientController { @GetMapping("/welcome") public ModelAndView welcome() { return new  ModelAndView("welcome"); } @GetMapping("/api/user") @PreAuthorize("hasAuthority('USER')") public Map<String, Object> apiUser() { } @GetMapping("/api/admin") @PreAuthorize("hasAuthority('ADMIN')") public Map<String, Object> apiAdmin() { } @GetMapping("/api/root") @PreAuthorize("hasAuthority('ROOT')") public Map<String, Object> apiRoot() { } }Copy the code

4 Comprehensive application

4.1 Permission Control Scheme

The following figure shows the basic authentication/authorization control scheme, which mainly designs the basic definition of the related data table on the authentication and authorization server. It can be understood by referring to the section “2.1 Life Examples” of this article.

4.2 Application in microservice architecture

Different from conventional service architecture, Authorization Server/Resource Server exists as a microservice in microservice architecture, and user login can be completed at one time through API gateway. No need to work with the Authorization Server that cannot jump to the Intranet.

Well, that’s all for today’s article. I hope you can really grasp the principle of Oauth2.0 single sign-on through this article. Finally, I am an architect who writes code and a programmer who makes architecture. I look forward to your attention. See you later!