Clean β’ Professional
OAuth2 and OpenID Connect (OIDC) are industry-standard protocols for authentication and authorization. While OAuth2 is primarily for authorization (granting access to resources), OIDC is an identity layer on top of OAuth2, providing authentication and user identity information.
OAuth2 is a framework for delegated access. Instead of sharing credentials, a client app receives access tokens to access resources on behalf of a user.
Key Roles in OAuth2:
| Role | Description |
|---|---|
| Resource Owner | User who owns the data |
| Client | Application requesting access |
| Authorization Server | Issues access tokens after authenticating the user |
| Resource Server | Hosts protected APIs and validates access tokens |
Flow (simplified):
User β Authorizes β Client β Requests Token β Access Resource
OIDC extends OAuth2 by adding authentication. It provides an ID Token (JWT) that contains user identity info like name, email, and roles.
OIDC Tokens:
| Token | Purpose |
|---|---|
| ID Token | Authenticate the user, contains user info |
| Access Token | Authorize API access (OAuth2 standard) |
| Refresh Token | Obtain new access token without re-login |
OIDC allows a client to verify the identity of the user and get profile info while using OAuth2 for authorization.
Flow (simplified):
User β Logs in β Authorization Server β ID Token + Access Token β Client
Step-by-step Flow:

Spring Security provides ready-made support for OAuth2 login and OIDC.
Integration Features:
Example: Spring Security OAuth2 Login
@Configuration
@EnableWebSecurity
publicclassSecurityConfig {
@Bean
public SecurityFilterChainsecurityFilterChain(HttpSecurity http)throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated())
.oauth2Login(oauth2 -> oauth2
.loginPage("/oauth2/authorization/my-client"))// Custom login page
.logout(logout -> logout
.logoutSuccessUrl("/"));
return http.build();
}
}
Key Components in Spring Security OAuth2
Spring Security uses Access Tokens and ID Tokens to manage authentication and authorization after an OAuth2/OIDC login.
Access Token: Grants access to APIs, contains scope, expiry, and client info, sent in Authorization header.
ID Token: Identifies the authenticated user, contains user info (sub, email, name), used by the client for authentication.
| Token | Contains | Usage |
|---|---|---|
| Access Token | Scope, expiry, client info | API access to resource server |
| ID Token | User info (sub, email, name) | Authentication, identify user in client |
Controller Example:
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.core.oidc.user.OidcUser;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
@GetMapping("/profile")
public String userProfile(@AuthenticationPrincipal OidcUser oidcUser) {
// Access ID Token info via OidcUser
return "Hello, " + oidcUser.getFullName() + " (" + oidcUser.getEmail() + ")";
}
}
@AuthenticationPrincipal gives access to OIDC user info after OAuth2 login.
Spring Security supports OAuth2 login, which allows users to authenticate using third-party identity providers (social logins) like:
Example (application.yml):
spring:
security:
oauth2:
client:
registration:
google:
client-id: your-client-id
client-secret: your-client-secret
scope: openid, profile, email
To protect APIs using access tokens:
@EnableWebSecurity
publicclassResourceServerConfig {
@Bean
public SecurityFilterChainsecurityFilterChain(HttpSecurity http)throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/api/admin/**").hasAuthority("SCOPE_admin")
.anyRequest().authenticated())
.oauth2ResourceServer(oauth2 -> oauth2
.jwt());
return http.build();
}
}
Access token scopes (SCOPE_admin) are used to enforce fine-grained authorization.
Keycloak can be used as Authorization Server:
1. Create realm, client, and roles
2. Configure Spring Boot with client credentials:
spring:
security:
oauth2:
client:
registration:
keycloak:
client-id: spring-client
client-secret: secret
scope: openid,profile,email
redirect-uri: "{baseUrl}/login/oauth2/code/keycloak"
provider:
keycloak:
issuer-uri: <http://localhost:8080/realms/myrealm>
3. Users login via Keycloak and receive ID token + access token
4. Roles are mapped to Spring Security authorities

Scopes: Define permissions for access tokens (read, write, admin)
Authorities: Mapped from scopes/roles for endpoint access control
Claims: Contain user info in ID Token (sub, email, name, roles)
Claims extraction example:
@GetMapping("/claims")
public Map<String, Object>getClaims(@AuthenticationPrincipal OidcUser oidcUser) {
return oidcUser.getClaims();
}
| Feature | OAuth2 + OIDC | JWT Only |
|---|---|---|
| Purpose | Auth + Authorization | Auth / Stateless API access |
| Tokens | Access, ID, Refresh | Access, Refresh |
| Identity | ID Token contains user info | JWT payload may contain user info |
| Protocol | Standardized OAuth2 / OIDC flows | Token validation only |
| Best Use | SSO, Enterprise apps | API security / microservices |
OAuth2 + OIDC is a modern, robust, and secure approach to handle authentication and authorization in enterprise-grade applications. By integrating Spring Security, developers can implement: