Understanding OAuth2 Single Sign-On (SSO) and Its Spring Boot Implementation

This article explains the principles of Single Sign-On using OAuth2.0, illustrates the flow with a real‑world analogy, details HTTP redirection, compares grant types, and provides a complete Spring Boot implementation of an authorization server, client application, and role‑based access control for microservices.

Code Ape Tech Column
Code Ape Tech Column
Code Ape Tech Column
Understanding OAuth2 Single Sign-On (SSO) and Its Spring Boot Implementation

1 What is Single Sign-On

1.1 Multi‑Point Login

In traditional multi‑point login systems each site maintains its own user database and login module, so users must log in separately to each site.

Authentication: verifying a user's identity.

Authorization: verifying a user's access permissions.

1.2 Single Sign-On (SSO)

SSO allows multiple sites (e.g., 192.168.1.20X) to share a single authentication/authorization server (e.g., 192.168.1.110). After a user logs in to any site, the login state is recognized by all other sites, enabling seamless access.

2 OAuth2 Authentication and Authorization Flow

2.1 Real‑World Example (Key)

To make the OAuth2.0 flow intuitive, imagine a scenario with a record bureau (client), a citizen (resource owner), and a police station (authorization server).

(1) Client: The record bureau holds specific resources (political, economic, etc.).

(2) Resource Owner: The citizen needs to access records from various bureaus.

(3) Authorization Server: Provides authentication and authorization services, storing bureau credentials, citizen credentials, and a mapping of citizen‑bureau permissions (often with a role layer).

2.1.1 First Visit to Record Bureau A

The citizen follows a series of redirects: registration → identity verification → authorization request → token issuance → access to the resource. The steps illustrate the OAuth2 Authorization Code grant.

2.1.2 First Visit to Record Bureau B

Because the citizen already possesses a valid token, many steps are skipped, and access is granted directly.

2.1.3 Subsequent Visits to Record Bureau A

All steps are bypassed; the existing session token provides immediate access.

2.2 HTTP Redirection Principle

When a server determines that a request belongs to another service, it issues an HTTP redirect to the appropriate URI, similar to being sent to another window in a government office.

2.3 SSO Workflow

The OAuth2 flow described above directly maps to the SSO process.

2.4 OAuth2 Grant Types (Advanced)

Authorization Code

: Used for server‑side applications (the mode demonstrated in this article). Implicit: Used for mobile or web apps running on the client device. Resource Owner Password Credentials: Used when the client is trusted. Client Credentials: Used for API access between services.

3 Implementing Authentication/Authorization with Spring Boot

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) Configuration of the Authorization Server

@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") // grant type
            .scopes("user_info")
            .autoApprove(true)
            .accessTokenValiditySeconds(3600); // 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");
    }
}

3.2 Client Application (Business Site)

(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) Web Security Configuration

@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 Role‑Based Permission Control

Define roles in the Authorization Server: USER, ADMIN/USER, ROOT/ADMIN/USER.

Annotate controller methods in the client to restrict access based on roles.

@RestController
public class Oauth2ClientController {
    @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 Permission Control Scheme

The diagram below shows the basic data model for authentication and authorization, which aligns with the life‑example described earlier.

4.2 Application in Microservice Architecture

In a microservice setup, the Authorization Server and Resource Server run as independent services. Users can log in through an API gateway in a single step without direct redirects to an internal Authorization Server.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

AuthenticationSpringBootAuthorizationSSO
Code Ape Tech Column
Written by

Code Ape Tech Column

Former Ant Group P8 engineer, pure technologist, sharing full‑stack Java, job interview and career advice through a column. Site: java-family.cn

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.