Mastering OAuth2 SSO: Real-World Scenarios and Spring Boot Guide

This article demystifies Single Sign-On using OAuth2.0 by illustrating the authentication and authorization flow through a real‑world analogy, explaining HTTP redirects, detailing the four grant types, and providing a complete Spring Boot implementation with role‑based access control for both client and server sides in microservice architectures.

Java Interview Crash Guide
Java Interview Crash Guide
Java Interview Crash Guide
Mastering OAuth2 SSO: Real-World Scenarios and Spring Boot Guide

What Is Single Sign-On (SSO)

Single Sign-On (SSO) allows users to log in once and access multiple domains without re‑authenticating. It contrasts with traditional multi‑point login where each site maintains its own user database and requires separate logins.

Key Concepts

Authentication : Verifying a user’s identity.

Authorization : Verifying a user’s access permissions.

OAuth2 Authorization Flow Explained with a Real‑World Analogy

The article uses an analogy of archive bureaus, a citizen, and a police station to illustrate OAuth2.0’s authentication and authorization steps.

Archive Bureau A (Client) – Represents a service that wants to access protected resources.

Citizen Zhang San (Resource Owner) – The user who owns the data.

Police Station (Authorization Server) – Central server that authenticates the user and issues authorization codes.

Zhang San visits Bureau A, is redirected to the police station for authentication (HTTP redirect).

After providing credentials, the police station issues an identity token.

The police station then issues an authorization code based on the citizen’s role (e.g., mayor) and the requested resource.

Bureau A exchanges the authorization code for an access token and accesses the archive.

The session token is now linked to the citizen, allowing seamless access to other bureaus.

HTTP Redirect Principle

When a browser request reaches a server that cannot handle the request, the server responds with an HTTP redirect, directing the client to another host or endpoint, similar to being sent to a different government office for the next step.

SSO Workflow Overview

The OAuth2.0 authentication/authorization process is summarized as a series of redirects and token exchanges, culminating in a single session token that grants access across multiple services.

OAuth2 Grant Types

Authorization Code – Server‑to‑server, most complex, used in this article.

Implicit – For mobile or web apps running on user devices.

Resource Owner Password Credentials – Trusted applications directly handle user credentials.

Client Credentials – For API access between services.

Spring Boot Implementation of Authentication/Authorization

Below are the essential configuration files and code snippets.

pom.xml (Dependency)

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

application.properties (Server Port)

server.port=8110  ## Listening port

Authorization Server Configuration

@EnableResourceServer
public class AuthorizationServerApplication {
    // ...
}
@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) // auto‑approve
            .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");
    }
}

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

Role‑Based Permission Control

@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() { /* ... */ }
}

Comprehensive Usage Diagram

Permission Control Scheme Diagram

SSO in Microservice Architecture

In a microservice setup, the Authorization Server and Resource Server run as independent services. An API gateway can handle the initial login, eliminating the need for client‑side redirects to internal servers.

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.

Spring BootOAuth2AuthorizationSingle Sign-On
Java Interview Crash Guide
Written by

Java Interview Crash Guide

Dedicated to sharing Java interview Q&A; follow and reply "java" to receive a free premium Java interview guide.

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.