Information Security 14 min read

Understanding OAuth2.0 Single Sign‑On (SSO) and Its Implementation with SpringBoot

This article explains the principles of Single Sign‑On using OAuth2.0, illustrates the workflow with a real‑world analogy, and provides a complete SpringBoot example—including authorization server, client configuration, role‑based access control, and micro‑service integration—so readers can master SSO implementation and security design.

Top Architect
Top Architect
Top Architect
Understanding OAuth2.0 Single Sign‑On (SSO) and Its Implementation with SpringBoot

Single Sign‑On (SSO) is a popular authentication method for multi‑domain enterprise sites. This article uses a real‑life scenario to clarify the OAuth2.0 SSO principle and then summarizes permission‑control solutions and their application in micro‑service architectures.

1 What is Single Sign‑On

1.1 Multi‑point Login

Traditional multi‑point login systems maintain separate user databases and login modules for each site, requiring users to log in manually to each site.

Authentication: verify a user's identity.

Authorization: verify a user's access permissions.

1.2 Single Sign‑On

SSO (Single Sign On) allows multiple sites to share a single authentication/authorization server. After logging in to any site, the user can access all other sites without re‑authentication.

2 OAuth2 Authentication & Authorization Flow

2.1 Real‑World Example (Key Point)

A life‑scenario is used to illustrate the OAuth2.0 flow:

(1) Client / 档案局A – the resource owner (e.g., a government archive agency).

(2) Resource Owner / 公民张三 – the user who needs to access resources.

(3) Authorization Server / 派出所 – provides authentication and authorization services.

Archive agency information (client‑id/secret).

User credentials (username/password) for authentication.

Permission mapping (roles) for authorization.

2.1.1 First Access to Archive A

The step‑by‑step interaction shows how the user is redirected to the authorization server, authenticates, receives an authorization code, exchanges it for a token, and finally accesses the protected resource.

2.1.2 First Access to Archive B

After obtaining a token from Archive A, the user can directly request a token for Archive B without repeating the full authentication flow.

2.1.3 Subsequent Access to Archive A

When the token is still valid, the user can directly access Archive A without any additional steps.

2.2 HTTP Redirect Principle

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

2.3 SSO Workflow Summary

The OAuth2.0 authentication/authorization process is summarized, encouraging readers to compare the diagram with the life‑example.

2.4 Advanced OAuth2.0

https://tools.ietf.org/html/rfc6749

https://tools.ietf.org/html/rfc6750

https://blog.csdn.net/seccloud/article/details/8192707

OAuth2.0 defines four grant types:

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

Implicit : for mobile or web apps running on the client device.

Resource Owner Password Credentials : for trusted applications.

Client Credentials : for API access between services.

3 Implementing Authentication & Authorization with 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) 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 (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) 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 user roles in the authorization server: user=USER, admin=ADMIN/USER, root=ROOT/ADMIN/USER.

Annotate controller methods with @PreAuthorize("hasAuthority('ROLE')") to enforce access.

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

    @GetMapping("/api/admin")
    @PreAuthorize("hasAuthority('ADMIN')")
    public Map
apiAdmin() { return Collections.emptyMap(); }

    @GetMapping("/api/root")
    @PreAuthorize("hasAuthority('ROOT')")
    public Map
apiRoot() { return Collections.emptyMap(); }
}

4 Comprehensive Application

4.1 Permission Control Scheme

A diagram (omitted) shows the basic data tables for authentication/authorization servers, which can be correlated with the life‑example in section 2.1.

4.2 Use in Micro‑Service Architecture

In micro‑service environments, the Authorization Server and Resource Server are separate services. Users can obtain tokens via an API gateway, eliminating the need for direct redirects to an internal authorization server.

Finally, the article provides a curated list of interview questions from major tech companies and invites readers to join a community for further discussion.

microservicesauthenticationSpringBootOAuth2authorizationSSORole-Based Access Control
Top Architect
Written by

Top Architect

Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.

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.