codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
🍃

Spring Boot

33 / 62 topics
33OAuth2 Basics in Spring Boot34Implementing OAuth2 in Spring Boot
Tutorials/Spring Boot/OAuth2 Basics in Spring Boot
🍃Spring Boot

OAuth2 Basics in Spring Boot

Updated 2026-04-20
3 min read

OAuth2 Basics in Spring Boot

Introduction

OAuth2 is an open-standard authorization protocol or framework that provides applications secure designated access. It allows third-party services to access user information without exposing passwords. This tutorial will guide you through the basics of implementing OAuth2 in a Spring Boot application, focusing on setting up an authorization server and securing resources.

Prerequisites

Before diving into the implementation, ensure you have the following:

  • Basic understanding of Spring Boot.
  • Java Development Kit (JDK) 8 or later installed.
  • An IDE like IntelliJ IDEA or Eclipse.
  • Maven or Gradle for dependency management.
  • A text editor or IDE to write code.

Setting Up a Spring Boot Project

Let's start by creating a new Spring Boot project. You can use Spring Initializr to generate the project structure. Choose the following options:

  • Project: Maven Project
  • Language: Java
  • Spring Boot: Latest stable version
  • Project Metadata:
    • Group: com.example
    • Artifact: oauth2-demo
    • Name: oauth2-demo
    • Description: OAuth2 Demo Application
    • Package name: com.example.oauth2demo
  • Packaging: Jar
  • Java: 8 or later
  • Dependencies: Spring Web, Spring Security

Download the generated project and import it into your IDE.

Configuring the Authorization Server

The authorization server is responsible for issuing tokens to clients. We'll use Spring Security OAuth2 to set up an authorization server.

Step 1: Add Dependencies

Add the following dependencies to your pom.xml:

<dependencies>
    <!-- Other dependencies -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.security.oauth.boot</groupId>
        <artifactId>spring-security-oauth2-autoconfigure</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.security.oauth.boot</groupId>
        <artifactId>spring-security-oauth2-authorization-server</artifactId>
    </dependency>
</dependencies>

Step 2: Configure the Authorization Server

Create a configuration class for the authorization server:

package com.example.oauth2demo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends AuthorizationServerConfigurerAdapter {

    private final AuthenticationManager authenticationManager;
    private final UserDetailsService userDetailsService;

    public SecurityConfig(AuthenticationManager authenticationManager, UserDetailsService userDetailsService) {
        this.authenticationManager = authenticationManager;
        this.userDetailsService = userDetailsService;
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
            .withClient("client")
            .secret("{noop}secret")
            .authorizedGrantTypes("password", "refresh_token")
            .scopes("read", "write");
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.authenticationManager(authenticationManager)
                 .userDetailsService(userDetailsService);
    }
}

Step 3: Configure User Details

Create a user details service to manage user authentication:

package com.example.oauth2demo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

@Configuration
public class UserDetailsConfig {

    @Bean
    public UserDetailsService userDetailsService() {
        InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
        manager.createUser(User.withUsername("user")
                               .password("{noop}password")
                               .roles("USER")
                               .build());
        return manager;
    }
}

Securing Resources

Now, let's secure a REST API using the token issued by the authorization server.

Step 1: Create a Resource Controller

Create a simple REST controller to expose a secured endpoint:

package com.example.oauth2demo.controller;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

    @GetMapping("/api/hello")
    @PreAuthorize("hasAuthority('SCOPE_read')")
    public String sayHello() {
        return "Hello, secured world!";
    }
}

Step 2: Configure Resource Server

Create a configuration class for the resource server:

package com.example.oauth2demo.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 ResourceServerConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .antMatchers("/api/**").authenticated()
            .and()
            .oauth2ResourceServer().jwt();
    }
}

Testing the OAuth2 Setup

To test the setup, you can use tools like Postman or curl.

Step 1: Obtain an Access Token

Use the following curl command to obtain an access token:

curl -X POST http://localhost:8080/oauth/token \
     -H "Authorization: Basic Y2xpZW50OnNlY3JldA==" \
     -d "grant_type=password&username=user&password=password"

This will return a JSON response with an access token.

Step 2: Access the Secured Resource

Use the obtained access token to access the secured resource:

curl http://localhost:8080/api/hello \
     -H "Authorization: Bearer <access_token>"

Replace <access_token> with the actual token you received in the previous step.

Best Practices

  1. Secure Client Credentials: Use a secure method to store client credentials, such as environment variables or a secrets management service.
  2. Token Storage: Consider using a database or an external service like Redis for storing tokens instead of keeping them in memory.
  3. Token Expiry and Refresh: Implement token expiry and refresh mechanisms to enhance security.
  4. Scopes and Authorities: Use scopes and authorities effectively to control access to resources.

Conclusion

This tutorial covered the basics of setting up OAuth2 in a Spring Boot application, including configuring an authorization server and securing resources. By following these steps, you can implement secure authentication and authorization for your applications using OAuth2.


PreviousUsing STOMP over WebSocketsNext Implementing OAuth2 in Spring Boot

Recommended Gear

Using STOMP over WebSocketsImplementing OAuth2 in Spring Boot