Information Security 12 min read

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

This article explains the principles and workflow of Single Sign‑On using OAuth2.0, illustrates the process with a real‑life analogy, and provides a complete Spring Boot example—including authorization server, client configuration, and role‑based access control—suitable for microservice architectures.

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

1. What Is Single Sign‑On

Traditional multi‑login systems require separate credentials for each site, while Single Sign‑On (SSO) allows a user to authenticate once and access multiple sites without re‑logging.

1.1 Multi‑Login

Each site maintains its own user database and login module; users must log in to each site individually.

Authentication: verifying a user's identity.

Authorization: verifying a user's access permissions.

1.2 Single Sign‑On (SSO)

Multiple sites share a central authentication and authorization server. After logging in to any site, the user can access all other sites without additional login steps.

2. OAuth2 Authentication and Authorization Flow

2.1 Real‑World Analogy (Key Example)

To illustrate OAuth2.0, the article uses a scenario involving a citizen (resource owner), several archives (resource servers), and a police station (authorization server). The steps demonstrate how the citizen obtains an authentication token and an authorization code to access protected resources across different archives.

2.1.1 First Visit to Archive A

The citizen registers, authenticates, receives an authorization code, exchanges it for a token, and then accesses the archive.

2.1.2 First Visit to Archive B

Because the citizen already holds a valid token, the process is streamlined, requiring only a few steps.

2.1.3 Subsequent Visits to Archive A

All previous steps are bypassed; the citizen directly accesses the archive using the existing token.

2.2 HTTP Redirection Principle

When a request reaches a server that cannot handle it, the server redirects the client to the appropriate host or endpoint, similar to being sent to another window in a government office.

2.3 SSO Workflow

The OAuth2.0 authentication/authorization process is summarized in a diagram that aligns with the real‑world example.

2.4 Advanced OAuth2.0

RFC 6749

RFC 6750

CSDN Article

OAuth2 defines four grant types:

Authorization Code : used for server‑side applications (the mode used in this article).

Implicit : used for mobile or web apps running on the user’s 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
public class AuthorizationServerApplication {
    // ...
}

(4) Authorization Server Configuration

@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 Access Control

Define roles in the authorization server: USER, ADMIN, ROOT.

Annotate controller methods with @PreAuthorize to restrict access based on roles.

@RestController
public class Oauth2ClientController {
    @GetMapping("/api/user")
    @PreAuthorize("hasAuthority('USER')")
    public Map
apiUser() { /* ... */ }

    @GetMapping("/api/admin")
    @PreAuthorize("hasAuthority('ADMIN')")
    public Map
apiAdmin() { /* ... */ }

    @GetMapping("/api/root")
    @PreAuthorize("hasAuthority('ROOT')")
    public Map
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, eliminating the need for direct interaction with an internal Authorization Server.

MicroservicesSpring BootauthenticationOAuth2authorizationSSOrole-based access
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

login 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.