Spring REST API Security Tutorial: Using OAuth2 + MySQL

Spring REST API Security Tutorial: Using OAuth2 + MySQL

Let's secure our Spring REST API with OAuth2 and MySQL. REST easy knowing your APIs are secure after this tutorial.

Let’s secure our Spring REST API with OAuth2 and MySQL. We will store user credentials in the MySQL database, and client credentials will be stored in the in-memory database. Every client has its own unique client ID.

To secure our REST API, we will have to do the following things:

  • Configure Spring Security and the database.

  • Configure the authorization server and resource server.

  • Get an access token and a refresh token.

  • Get a protected Resource (REST API) using an access token.

Before we start, let's look at some basic concepts related to Spring Security OAuth2.

You may also like: Spring Security Tutorial: Simple Authentication with Spring Boot.

OAuth2 Roles

Resource Owner

A resource owner is a person (like an end-user) in an application that owns the service or security policy.

Resource Server

This is the resource server hosting the protected resource or service.

Client Application

The client application is the application requesting access to resources stored on the resource server. The client application also obtains authorization from the resource owner.

Authorization Server

The authorization server is the server authorizing the client app to access the resources of the resource owner.


Let's start to secure our REST API endpoints.

First, we need to enable Spring Security to add the security feature in the application. To configure and enable Spring Security, the @EnableWebSecurity annotation is used.

By using @EnableGlobalMethodSecurity, we can easily secure our methods with Java configurations. Global method security will activate  @PreFilter@PostFilter , @PreAuthorize, and the @PostAuthorize  annotations if we want to use them.

@EnableGlobalMethodSecurity(securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
  UserDetailsServiceImpl userDetailsService;
  protected void configure(HttpSecurity http) throws Exception {
  public DaoAuthenticationProvider authenticationProvider() {
    DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
    provider.setPasswordEncoder( bCryptPasswordEncoder() );
    return provider;
  public BCryptPasswordEncoder bCryptPasswordEncoder() {
    return new BCryptPasswordEncoder();
  public AuthenticationManager authenticationManagerBean() throws Exception {
    return super.authenticationManagerBean();
  public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {


  • Here, WebSecurityConfigurerAdapter  is used to customize security implementation.

  • Endpoint /OAuth/tpken is used to request a token (access or refresh).

  • We inject a custom implementation of UserDetailsService in order to retrieve user details from the database.

  • We use the defined BCryptPasswordEncoder bean for password encoding.

Now, we need to configure the authorization server. The @EnableAuhtorizationServer  annotation enables an authorization server. AuthorizationServerConfigurerAdapter  implements the  AuthorizationServerConfigurer, which provides all the necessary methods to configure an Authorization server. It also contains information about registered clients and possible access to scopes and grant types.

public class OAuthConfiguration extends AuthorizationServerConfigurerAdapter {
  private AuthenticationManager authenticationManager;
  UserDetailsService userDetailsService;
  public void configure(final AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
  public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
      .authorizedGrantTypes("password", "authorization_code", "refresh_token").scopes("read","write")
  public void configure(final AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
  public TokenStore tokenStore(){
    return new JwtTokenStore(defaultAccessTokenConverter());
  public JwtAccessTokenConverter defaultAccessTokenConverter() {
    JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
    return converter;

Notes on the above configuration:

  • Registers a client with client-id ‘fooClientId’ and password ‘ secret’ and the roles and scope they are allowed.

  • Specifies authorized grant types (password, authorization_code, refresh_token).

  • Specifies the JwtTokenStore to store tokens.

Next, we need to configure the resource server. The @EnableResourceServer  annotation, applied on OAuth2 Resource Servers, enables a Spring Security filter that authenticates requests using an incoming OAuth2 token.

The class ResourceServerConfigurerAdapter implements the ResourceServerConfigure,  providing methods to adjust the access rules and paths that are protected by OAuth2 security.

public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
    private static final String RESOURCE_ID = "resource-server-rest-api";
    public void configure(ResourceServerSecurityConfigurer resources) {
    public void configure(HttpSecurity http) throws Exception {

Next, we need to update the application.properties to configure the MySQL database. Create the user_management schema in MySQL and add the user table to store user credentials with roles.

spring.datasource.url = jdbc:mysql://localhost:3306/user_management
spring.datasource.username = root
spring.datasource.password = root

# Hibernate ddl auto (create, create-drop, update)
spring.jpa.hibernate.ddl-auto = update

# Naming strategy
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy

# Use spring.jpa.properties.* for Hibernate native properties (the prefix is
# stripped before adding them to the entity manager)

# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
server.port = 8080

Test Application

To access any secured REST API endpoint, first, we will have to get the access token. To get the access token, we will need to add an authorization header with client credentials and add the request body with user credentials in postman.

After receiving the access token and refresh token, we can access any secured REST API endpoints using access token. When the access token expired, the refresh token is used to get a new access token.

I have attached some of postmen request responses


This is image title


This is image title


This is image title

You can refer to the whole project on GitHub.

Thank for reading. I hope this tutorial will surely help and you if you liked this tutorial, please consider sharing it with others

Originally published on dzone.com

spring-boot mysql security api web-development

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Top 10 API Security Threats Every API Team Should Know

Learn what are the most important API security threats engineering leaders should be aware of and steps you can take to prevent them

Json Web Token: How to Secure a Spring Boot REST API - DZone Security

In this post, I show how to secure Spring Boot REST API using Json Web Tokens for authorization. We will also use Spring Security in this tutorial.

Set up Web App with Spring Boot and Spring Security

Download the Spring Boot Web App Example Project. Run the Initial Web App. Add Project Dependencies for Your Spring Boot + Spring Security Web App. Understand Your Spring Boot App. Set Up Okta for OAuth 2.0 Single Sign-On. Configure Your Spring Boot App for Single SignOn (SSO) Refine Our Permissions

Json Web Token: How to Secure Spring Boot REST API

In this post, I will show how to secure your spring boot based REST API. It has been more of a trend to secure REST APIs to avoid any…

Hire Web Developer

Looking for an attractive & user-friendly web developer? HourlyDeveloper.io, a leading web, and mobile app development company, offers web developers for hire through flexible engagement models. You can **[Hire Web...