Secure Spring Boot applications with OAuth2 authentication: Step-by-step guide
Posted By
Nikhil Barse
If you've been building Spring Boot apps with basic form logins, you've probably hit the point where you need something better. Maybe your company uses Okta, Azure AD, or some other identity provider. Maybe you want to stop managing passwords altogether. That's where OAuth2 authentication comes in.
Spring Boot OAuth2 authentication is an enterprise-grade authentication mechanism that delegates credential management to trusted identity providers. This comprehensive guide walks through implementing OAuth2 in a Spring Boot application with role-based access control, so you can restrict pages to specific users.
If you're new to Spring Security, check out our guide on custom authentication strategies first—it covers the basics before you tackle OAuth2.
This guide covers implementing OAuth2 in a Spring Boot application, including role-based access control so you can restrict pages to specific users. If you need enterprise-level authentication and are considering other approaches, SAML authentication is another solid option worth knowing about.
What is OAuth2 authentication?
OAuth2 authentication is an open standard authorization protocol that allows users to grant third-party applications access to their resources without sharing passwords. In the context of Spring Boot applications, OAuth2 enables Single Sign-On (SSO) by delegating user authentication to an external identity provider.
Simply put: instead of your application storing and validating passwords, OAuth2 authentication in Spring Boot lets an external provider (like Okta or Azure AD) handle login. Your app receives a secure token that confirms the user's identity.
OAuth2 gets talked about a lot, and honestly, it's simpler than people make it sound. At its core, you're outsourcing authentication to a third party. Your users log in somewhere else (like Okta or Google), get a token, and then that token tells your app who they are and what they can do.
If you're coming from a homegrown authentication system or the approach covered in custom authentication implementations, OAuth2 represents a significant shift—you're trusting an external provider instead of managing credentials yourself.
How does OAuth 2.0 work?
OAuth 2.0 operates through a series of steps called the OAuth2 authorization flow. Here's how Spring Boot OAuth2 authentication works in practice:
- User initiates login: The user clicks "Log in" on your Spring Boot application.
- Redirect to identity provider: Your app redirects them to your configured identity provider (authorization server).
- User authenticates: The user enters their credentials at the identity provider, not your app.
- Authorization grant: The identity provider gives your app an authorization code.
- Token exchange: Your Spring Boot backend exchanges this code for an access token (and optionally a refresh token).
- Access granted: Your app uses the access token to identify the user and verify their roles.
- User logged in: The user gains access to your application's protected resources.
Key players in OAuth 2.0
- Resource owner: The person trying to log in.
- Authorization server: The system that verifies their identity (Okta, Azure AD, Google, etc.).
- OAuth2 client: Your Spring Boot application.
- Resource server: Any APIs you want to protect using the access token.
The beauty of this token-based authentication setup is you never touch passwords. The user logs in once at their identity provider, gets a token, and uses that everywhere.
OAuth2 implementation in Spring Boot: Step-by-step
Step 1: Add the dependency
If you're using Maven, add this to pom.xml:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
For Gradle users, add this to build.gradle:
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-oauth2-client'
}
That's it. Spring Boot handles most of the heavy lifting for you.
Step 2: Configure Spring security
Create a SecurityConfig class. This is where you tell Spring how authentication should work. Enable method-level security too—you'll need it for role checks.
@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
// Require HTTPS (important for OAuth2 in production)
.requiresChannel(channel ->
channel.anyRequest().requiresSecure()
)
// Define which endpoints are public and which need authentication
.authorizeHttpRequests(authorize ->
authorize
.requestMatchers("/", "/access-denied").permitAll()
.anyRequest().authenticated()
)
// Enable OAuth2 login and map roles from your identity provider
.oauth2Login(oauth2 ->
oauth2.userInfoEndpoint(userInfo ->
userInfo.userAuthoritiesMapper(userAuthoritiesMapper())
)
)
// Handle logout
.logout(logout ->
logout
.logoutSuccessUrl("/")
.permitAll()
)
// Redirect to a proper page when access is denied
.exceptionHandling(exceptions ->
exceptions.accessDeniedPage("/access-denied")
);
return http.build();
}
}
Note on HTTPS: If you're testing locally on localhost, the HTTPS requirement will cause connection errors. Comment out the .requiresChannel() block while developing, but keep it in production.
Step 3: Configure your identity provider
Tell Spring where your identity provider is and provide the credentials. Add this to application.yml. Here's an example using Okta:
spring:
security:
oauth2:
client:
registration:
okta:
client-id: your-client-id
client-secret: your-client-secret
scope:
- openid
- profile
- email
authorization-grant-type: authorization_code
redirect-uri: "{baseUrl}/login/oauth2/code/{registrationId}"
provider:
okta:
issuer-uri: https://your-domain.okta.com/oauth2/default
Replace issuer-uri, client-id, and client-secret with values from your identity provider. The redirect-uri is where your app receives the token after login—Spring handles this automatically, no controller needed.
The openid scope is required. Without it, Spring won't get the ID token needed to extract user details.
Step 4: Map OAuth2 roles with Spring security
Here's the tricky part of Spring Security implementation steps. Your identity provider probably sends user groups or roles in the token, but Spring Security expects them in a specific format: with a ROLE_ prefix. This is where role-based access control truly comes into play.
Add this to your SecurityConfig:
@Bean
public GrantedAuthoritiesMapper userAuthoritiesMapper() {
return (authorities) -> {
Set<GrantedAuthority> mappedAuthorities = new HashSet<>();
mappedAuthorities.addAll(authorities);
authorities.forEach(authority -> {
if (authority instanceof OidcUserAuthority oidcAuth) {
// Extract groups from the token
List<String> groups = oidcAuth.getIdToken().getClaimAsStringList("groups");
if (groups != null) {
for (String group : groups) {
// Add the ROLE_ prefix so Spring recognizes it
mappedAuthorities.add(new SimpleGrantedAuthority("ROLE_" + group.toUpperCase()));
}
}
}
});
return mappedAuthorities;
};
}
This interceptor runs during login and transforms your provider's groups into Spring roles. Make sure your identity provider is configured to include groups in the ID token. In Okta, you'll need to add a custom claim called groups in your Authorization Server settings.
Step 5: Test it out
Write a simple controller to verify everything works:
@RestController
public class HomeController {
@GetMapping("/")
public String home(@AuthenticationPrincipal OAuth2User principal) {
if (principal == null) {
return "Public page. Log in to see protected content.";
}
return "Welcome back, " + principal.getAttribute("name");
}
// Only admins can access this
@PreAuthorize("hasRole('ADMIN')")
@GetMapping("/admin")
public String adminPanel() {
return "Admin Dashboard";
}
@GetMapping("/access-denied")
public String accessDenied() {
return "403 Forbidden: You don't have permission to access this.";
}
}
Run the app. When you hit a protected endpoint, you'll be redirected to your identity provider's login page. After login, you'll be back in your app with a token and whatever roles your provider sent.
Implementing OAuth2 authentication in Spring Boot
Spring Boot OAuth2 authentication is the modern standard for securing enterprise applications. By delegating authentication to trusted identity providers, you eliminate the burden of password management while improving user experience through Single Sign-On.
The implementation process—while it looks intimidating at first with all the configuration—boils down to these key points:
- Spring Security handles the heavy lifting automatically through the
spring-boot-starter-oauth2-clientdependency. - OAuth2 implementation in Spring Boot requires minimal configuration when your identity provider is properly set up.
- Role-based access control works seamlessly with
@PreAuthorizeannotations once you map external roles correctly. - Token-based authentication is more secure than password-based approaches for modern applications.
- Spring Boot security best practices must include HTTPS, token validation, and proper token management.
Once everything is wired up in your Spring Boot application, users get a seamless experience—they authenticate once at their company's identity provider and gain access everywhere without managing new passwords. Your team gets cleaner, more secure code. The whole system becomes enterprise-ready from day one.
If you're ready to move beyond basic authentication, Spring Boot OAuth2 security is the natural next step for modern applications handling sensitive data and multiple user roles.
Implementing OAuth2 in production? Opcito can help
Implementing OAuth2 can feel overwhelming. If you're stuck or need guidance on securing your Spring Boot application, contact our experts to discuss your requirements and get personalized help with your implementation.
At Opcito, we specialize in building enterprise-grade Spring Boot applications with robust security architectures. Our team has extensive experience implementing OAuth2, SSO, and role-based access control across complex microservice environments. Let us help you navigate the security landscape and get your application production-ready.
Related Blogs













