0
0
SpringbootHow-ToBeginner · 4 min read

How to Implement OAuth2 in Spring Boot: Simple Guide

To implement OAuth2 in Spring Boot, add spring-boot-starter-oauth2-client or spring-boot-starter-oauth2-resource-server dependencies, then configure security properties in application.yml or application.properties. Use @EnableWebSecurity and customize SecurityFilterChain to enable OAuth2 login or resource server features.
📐

Syntax

Implementing OAuth2 in Spring Boot involves these parts:

  • Dependencies: Add OAuth2 client or resource server starter.
  • Configuration: Define OAuth2 provider details in application.yml or application.properties.
  • Security Setup: Use @EnableWebSecurity and configure a SecurityFilterChain bean to enable OAuth2 login or resource server.
java/yaml
dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-oauth2-client'
    // or for resource server
    implementation 'org.springframework.boot:spring-boot-starter-oauth2-resource-server'
}

# application.yml example
spring:
  security:
    oauth2:
      client:
        registration:
          google:
            client-id: your-client-id
            client-secret: your-client-secret
            scope: openid,profile,email
        provider:
          google:
            authorization-uri: https://accounts.google.com/o/oauth2/v2/auth
            token-uri: https://oauth2.googleapis.com/token
            user-info-uri: https://openidconnect.googleapis.com/v1/userinfo
            user-name-attribute: sub

// Security configuration class
@EnableWebSecurity
public class SecurityConfig {
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
          .authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
          .oauth2Login();
        return http.build();
    }
}
💻

Example

This example shows a Spring Boot app that uses Google OAuth2 login to secure all pages. It configures client details in application.yml and sets up security to require login.

java/yaml
package com.example.oauth2demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;

@SpringBootApplication
public class Oauth2DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(Oauth2DemoApplication.class, args);
    }

    @EnableWebSecurity
    public static class SecurityConfig {
        @Bean
        public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
            http
              .authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
              .oauth2Login();
            return http.build();
        }
    }
}

# application.yml
spring:
  security:
    oauth2:
      client:
        registration:
          google:
            client-id: your-google-client-id
            client-secret: your-google-client-secret
            scope:
              - openid
              - profile
              - email
        provider:
          google:
            authorization-uri: https://accounts.google.com/o/oauth2/v2/auth
            token-uri: https://oauth2.googleapis.com/token
            user-info-uri: https://openidconnect.googleapis.com/v1/userinfo
            user-name-attribute: sub
Output
When running, the app redirects unauthenticated users to Google login page. After login, users access the app pages securely.
⚠️

Common Pitfalls

Common mistakes when implementing OAuth2 in Spring Boot include:

  • Missing or incorrect client ID and secret in configuration.
  • Not setting user-name-attribute correctly, causing user info extraction to fail.
  • Forgetting to enable oauth2Login() or oauth2ResourceServer() in security config.
  • Using legacy WebSecurityConfigurerAdapter instead of the modern SecurityFilterChain bean.
java
/* Wrong: Using deprecated WebSecurityConfigurerAdapter */
@EnableWebSecurity
public class OldSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().anyRequest().authenticated()
            .and().oauth2Login();
    }
}

/* Right: Use SecurityFilterChain bean */
@EnableWebSecurity
public class SecurityConfig {
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
            .oauth2Login();
        return http.build();
    }
}
📊

Quick Reference

Summary tips for OAuth2 in Spring Boot:

  • Use spring-boot-starter-oauth2-client for login clients.
  • Configure OAuth2 providers in application.yml with client ID, secret, and endpoints.
  • Define a SecurityFilterChain bean with oauth2Login() or oauth2ResourceServer().
  • Test with real OAuth2 providers like Google or GitHub.

Key Takeaways

Add the correct OAuth2 starter dependency for client or resource server.
Configure OAuth2 client details properly in application properties or YAML.
Use SecurityFilterChain bean with oauth2Login() to enable OAuth2 login.
Avoid deprecated WebSecurityConfigurerAdapter; use modern configuration.
Test OAuth2 flow with a real provider to ensure correct setup.