Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Spring Security and OAuth2

OAuth2 is an industry-standard protocol for authorization. Spring Security provides robust support for integrating with OAuth2. This guide covers the key concepts and steps for setting up OAuth2 authentication in your Spring Boot application, including setting up dependencies, configuring OAuth2 client, and securing endpoints.

Key Concepts of Spring Security and OAuth2

  • OAuth2: A protocol for authorization, allowing third-party applications to access user resources without exposing user credentials.
  • OAuth2 Client: Configures the client application that will interact with the OAuth2 authorization server.
  • OAuth2 Resource Server: A server that hosts protected resources and validates access tokens.
  • Authorization Server: The server that issues access tokens to the client.

Adding Dependencies

Include the Spring Security OAuth2 dependencies in your pom.xml file:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>

Configuring OAuth2 Client

Configure the OAuth2 client by specifying the client details and authorization server settings:

Example: application.yml

spring:
  security:
    oauth2:
      client:
        registration:
          google:
            client-id: YOUR_CLIENT_ID
            client-secret: YOUR_CLIENT_SECRET
            scope: profile, email
            redirect-uri: "{baseUrl}/login/oauth2/code/{registrationId}"
            authorization-grant-type: authorization_code
        provider:
          google:
            authorization-uri: https://accounts.google.com/o/oauth2/auth
            token-uri: https://oauth2.googleapis.com/token
            user-info-uri: https://www.googleapis.com/oauth2/v3/userinfo

Configuring Security

Configure security to enable OAuth2 login and protect specific endpoints:

Example: SecurityConfiguration.java

// SecurityConfiguration.java
package com.example.myapp.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
            .antMatchers("/", "/login**", "/error").permitAll()
            .anyRequest().authenticated()
            .and()
            .oauth2Login()
            .loginPage("/login")
            .defaultSuccessURL("/home", true)
            .failureURL("/login?error=true");
    }
}

Securing Endpoints

Protect specific endpoints by specifying access rules:

Example: SecurityConfiguration.java

// SecurityConfiguration.java
@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests()
        .antMatchers("/", "/login**", "/error").permitAll()
        .antMatchers("/admin/**").hasRole("ADMIN")
        .anyRequest().authenticated()
        .and()
        .oauth2Login();
}

Using JWT Tokens

If using JWT tokens, configure the resource server to validate them:

Example: application.yml

spring:
  security:
    oauth2:
      resourceserver:
        jwt:
          issuer-uri: https://issuer.example.com

Example: Full Configuration

Here is a full example combining client configuration and security settings:

Example: application.yml

spring:
  security:
    oauth2:
      client:
        registration:
          google:
            client-id: YOUR_CLIENT_ID
            client-secret: YOUR_CLIENT_SECRET
            scope: profile, email
            redirect-uri: "{baseUrl}/login/oauth2/code/{registrationId}"
            authorization-grant-type: authorization_code
        provider:
          google:
            authorization-uri: https://accounts.google.com/o/oauth2/auth
            token-uri: https://oauth2.googleapis.com/token
            user-info-uri: https://www.googleapis.com/oauth2/v3/userinfo
      resourceserver:
        jwt:
          issuer-uri: https://issuer.example.com

Example: SecurityConfiguration.java

// SecurityConfiguration.java
package com.example.myapp.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
            .antMatchers("/", "/login**", "/error").permitAll()
            .antMatchers("/admin/**").hasRole("ADMIN")
            .anyRequest().authenticated()
            .and()
            .oauth2Login()
            .loginPage("/login")
            .defaultSuccessURL("/home", true)
            .failureURL("/login?error=true")
            .and()
            .oauth2ResourceServer()
            .jwt();
    }
}

Key Points

  • OAuth2: A protocol for authorization, allowing third-party applications to access user resources without exposing user credentials.
  • OAuth2 Client: Configures the client application that will interact with the OAuth2 authorization server.
  • OAuth2 Resource Server: A server that hosts protected resources and validates access tokens.
  • Authorization Server: The server that issues access tokens to the client.
  • Include the Spring Security OAuth2 dependencies in your pom.xml file.
  • Configure the OAuth2 client by specifying the client details and authorization server settings.
  • Configure security to enable OAuth2 login and protect specific endpoints.
  • Protect specific endpoints by specifying access rules.
  • If using JWT tokens, configure the resource server to validate them.

Conclusion

Integrating OAuth2 with Spring Security allows you to leverage the power of OAuth2 for secure authorization in your Spring Boot applications. By understanding and configuring the OAuth2 client, resource server, and security settings, you can ensure secure access to your application's resources. Happy coding!