OAuth 2 realizes single sign on, which is easy to understand!

Author: Wang Kefeng\
source: https://kefeng.wang/2018/04/0...

Single sign on is a popular login method for multi domain name enterprise sites. In this paper, real-life scenes are used to assist understanding, and strive to completely clarify oauth2 0 principle and process of single sign on. At the same time, the implementation scheme of permission control and its application in microservice architecture are summarized.

1 what is single sign on

1.1 multipoint login

In the traditional multipoint login system, each site implements its own special account database and login module. The login status of each site does not recognize each other, and each site needs to log in manually one by one. As shown in the figure below, two terms have the following meanings:

  • Authentication: verify the identity of the user;
  • Authorization: verify the user's access rights.

1.2 single sign on

Single Sign On, English is Single Sign On, abbreviated as SSO. Multiple sites (192.168.1.20X) share one authentication and authorization server (192.168.1.110, shared by user database and authentication and authorization module). After logging in through any of these sites (such as 192.168.1.201), users can access all other sites without logging in. Moreover, each site can interact directly through the login status.

2 principle and process of oauth2 authentication and authorization

2.1 life examples [★★ key points ★★]

In order to intuitively understand oauth2 0 principle process, we assume such a life scenario:

(1) Archives Bureau a (client / Client): identified by "Archives Bureau ID / password", it is an organization that holds archives resources. There are many archives bureaus B/C /... In parallel. The archives contents (Resources / resources) stored in each archives bureau are different, such as politics, economy, military, culture, etc;

(2) Citizen Zhang San (resource owner / Resource Owner): identified by "user name / password", you need to check the files in each Archives Bureau;

(3) Police station (authorization server / Authentication Server): it can be a single huge police station or a police station cluster with data sharing. The information in charge and the external interface functions provided include:

  • Archives Bureau Information: the "Archives Bureau ID / password" of all archives bureaus to prove the identity of the Archives Bureau;
  • Citizen information: the "user name / password" of all citizens can provide Zhang San's user identification (authentication / Authentication)
  • Citizen's authority over the Archives Bureau: there is a mapping table of the authority of citizens and the Archives Bureau, which can check whether each citizen has operation authority (Authorization) over each Archives Bureau. Usually, an official position (role / Role) layer will be added in the design, which official position (Role) each citizen belongs to and which official position (Role) has operation authority for a specific Archives Bureau.

2.1.1 Zhang San's first visit to Archives Bureau A

Zhang San had never visited the Archives Bureau before. He came to the Archives Bureau for the first time. Understand by referring to the serial number in the figure below:

(1) Zhang San came to the "archives office" of "Archives Bureau A", where he asked for real name registration before inquiry, and was instructed to go to the "user registry" (HTTP redirection);

(2) When Zhang San came to the "user registry" of "Archives Bureau a", he could neither prove his identity (authentication) nor prove that he had the authority (authorization) to check archives a. Zhang San carries the client ID of Archives Bureau A and is redirected to the "issuing office of authorization letter";

(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). The office requires to prove identity (authentication) first and is redirected to the "user authentication office";

(4) Zhang San went to the "user authentication office" of the "police station" and received the user identity form (web login Form);

(5) Zhang San fills in his user name and password and submits it to (submit / Submit) "user authentication office", where the user name and password match from the private database, determines that this person is Zhang San, issues an identity certificate and completes the authentication. Zhang San took the identification letter and the logo of Archives Bureau A and was redirected to the "issuing office of authorization letter";

(6) Zhang San came to the "authorization letter issuing office" again to show his identity certificate and the identification of Archives Bureau A. according to the private database, Zhang San's official position is at the mayor level (role). This official position has the query authority of Archives Bureau a, so he issued the authorization letter (authorization code) of "allowing Zhang San to query Archives Bureau a", Zhang San took the authorization letter and was redirected to the "user login office" of the "Archives Bureau";

(7) When Zhang San arrives at the "user login office" of the "Archives Bureau", the office privately takes out the client ID and password of Archives Bureau A, attaches the authorization letter (code) presented by Zhang San, and applies to the "waist token issuing office" of the "police station" for Zhang San's "waist token". Zhang San can bring this waist token to show his identity and authority. Redirected to "archives";

(8) Zhang San's session has been associated with a token. You can check the file directly through the "file office".

2.1.2 Zhang San's first visit to Archives Bureau B

Zhang San has successfully visited Archives Bureau A. now he wants to visit Archives Bureau B. Understand by referring to the serial number in the figure below:

(1) (2) ditto;

(3) Zhang San already has an "identity certificate" and successfully issued an authorization letter for "visiting Archives Bureau B" directly at the "authorization letter issuing office" of the "police station";

(4) / (5) / (6) no;

(7) The "user registry" of "Archives Bureau B" completes the registration;

(8) The "archives office" of "Archives Bureau B" found the archives.

2.1.3 Zhang San visits Archives Bureau A again

Zhang San has successfully visited Archives Bureau A. now he wants to visit Archives Bureau a. Understand by referring to the serial number in the figure below:

(1) Directly and successfully found the file;

(2 ~ 8) are exempted.

2.2 HTTP redirection principle

In the HTTP protocol, after the REQUEST of the browser is sent to the server, if the server finds that the business does not belong to its own jurisdiction, it will send you to an interface (uri) of its own server or other servers (hosts). Just as we go to the government department, every time we go to A window, the staff will say "you take material A to the X window of our institute or the Z window of other Y Institute" for the next procedure.

2.3 SSO workflow

So far, it is not difficult to understand the authentication / authorization process of OAuth 2.0, which will not be repeated here. Please take the following figure and compare it with the section "2.1 life examples".

2.4 OAuth2.0 advanced

According to the official standard, OAuth 2.0 shares four authorization modes:

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

3 authentication / authorization based on SpringBoot

3.1 authorization server

(1) pom.xml

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

(2) application.properties

server.port=8110 ## Listening port

(3) AuthorizationServerApplication.java

@EnableResourceServer // Enable resource server
public class AuthorizationServerApplication {
    // ...
}

(4) Configure the parameters of the authorization service

@Configuration
@EnableAuthorizationServer
public class Oauth2AuthorizationServerConfigurer extends AuthorizationServerConfigurerAdapter {
    @Override
    public void configure(final ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient("webapp").secret("secret") //Client id/secret
                .authorizedGrantTypes("authorization code") //Authorized mother mode
                .scopes("user_info")
                .autoApprove(true) //Automatic approval
                .accessTokenValiditySeconds(3600); //Validity 1hour
    }
}

@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");
    }
}

3.2 Client (Client, business website)

(1) pom.xml

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

(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

(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");
    }
}

3.3 user permission control (role-based)

  • In the authorization server, define the roles owned by each user: user=USER, admin=ADMIN/USER, root=ROOT/ADMIN/USER
  • In the business website (client), the annotation indicates which roles can be used
@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() {
    }
}

4 comprehensive application

4.1 authority control scheme

The following figure is the basic authentication / authorization control scheme, which mainly designs the basic definitions of relevant data tables on the authentication and authorization server. It can be understood by referring to the section "2.1 life examples" in this article.

4.2 application in microservice architecture

Different from the conventional service architecture, in the microservice architecture, the Authorization Server/Resource Server exists as a microservice. The user's login can be completed at one time through the API gateway without the Authorization Server that cannot jump to the intranet.

Recent hot article recommendations:

1.1000 + Java interview questions and answers (2022 latest version)

2.Hot! The Java collaboration is coming...

3.Spring Boot 2.x tutorial, too complete!

4.Spring Boot 2.6 was officially released, a wave of new features..

5.Java development manual (Songshan version) is the latest release. Download it quickly!

Feel good, don't forget to like + forward!

Keywords: Java

Added by mikesch on Tue, 04 Jan 2022 13:24:18 +0200