Spring Boot – OAuth2 Authorization and Resource Servers

In this Spring security oauth2 tutorial, learn to build an authorization server to authenticate your identity to provide access_token, which you can use to request data from the resource server.

1. Introduction to OAuth 2

OAuth 2 is an authorization method to provide access to protected resources over the HTTP protocol. Primarily, oauth2 enables a third-party application to obtain limited access to an HTTP service –

  • either on behalf of a resource owner by orchestrating an approval interaction between the resource owner and the HTTP service
  • or by allowing the third-party application to obtain access on its own behalf.

1.1. Roles

OAuth defines four roles –

  • Resource Owner – The user of the application.
  • Client – the application (user is using) which require access to user data on the resource server.
  • Resource Server – store user’s data and http services which can return user data to authenticated clients.
  • Authorization Server – responsible for authenticating user’s identity and gives an authorization token. This token is accepted by resource server and validate your identity.
Oauth2 Flow
Oauth2 Flow

1.2. Access Token vs Refresh Token

An access token is a string representing an authorization issued to the client. Tokens represent specific scopes and durations of access, granted by the resource owner, and enforced by the resource server and authorization server.

The refresh token is issued (along with the access token) to the client by the authorization server, and it is used to obtain a new access token when the current access token becomes invalid or expires. The refresh token is also used to get additional access tokens with identical or narrower scope (access tokens may have a shorter lifetime and fewer permissions than authorized by the resource owner). Issuing a refresh token is optional at the discretion of the authorization server.

  • The responsibility of access token is to access data before it gets expired.
  • The responsibility of refresh token is to request for a new access token when the existing access token is expired.

2. Oauth2 – Authorization Server

To create an authorization server using spring security oauth2 module, we need to use annotation @EnableAuthorizationServer and extend the class AuthorizationServerConfigurerAdapter.

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
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.AuthorizationServerSecurityConfigurer;
public class OAuth2AuthorizationServer extends AuthorizationServerConfigurerAdapter 
    private BCryptPasswordEncoder passwordEncoder;
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
            .authorizedGrantTypes("password", "authorization_code", "refresh_token")

Spring security OAuth exposes two endpoints for checking tokens (/oauth/check_token and /oauth/token_key) which are by default protected behind denyAll(). The tokenKeyAccess() and checkTokenAccess() methods open these endpoints for use.

The ClientDetailsServiceConfigurer is used to define an in-memory or JDBC implementation of the client details service. We have used in-memory implementation. It has the following important attributes:

  • clientId – (required) the client id.
  • secret – (required for trusted clients) the client secret, if any.
  • scope – The scope to which the client is limited. If the scope is undefined or empty (the default), the client is not limited by scope.
  • authorizedGrantTypes – Grant types that are authorized for the client to use. The default value is empty.
  • authorities – Authorities that are granted to the client (regular Spring Security authorities).
  • redirectUris – redirects the user-agent to the client’s redirection endpoint. It must be an absolute URL.

3. Oauth2 – Resource Server

To create a resource server component, use @EnableResourceServer annotation and extend the ResourceServerConfigurerAdapter class.

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;

public class OAuth2ResourceServer extends ResourceServerConfigurerAdapter
	public void configure(HttpSecurity http) throws Exception {

Above config enable protection on all endpoints starting /api. All other endpoints can be accessed freely.

The resource server also provides a mechanism to authenticate users themselves. It will be a form-based login in most cases.

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

public class SecurityConfig extends WebSecurityConfigurerAdapter {

    protected void configure(HttpSecurity http) throws Exception {
	        	.antMatchers("/oauth/authorize**", "/login**", "/error**")

    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

    public BCryptPasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();

Above WebSecurityConfigurerAdapter class setup a form-based login page and open up the authorization urls with permitAll().

4. Oauth2 Protected REST Resources

For demo purposes, I have created only one API which returns the logged-in user’s name and email.

import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

public class RestResource
	public ResponseEntity<UserProfile> profile()
		//Build some dummy data to return for testing
		User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		String email = user.getUsername() + "@howtodoinjava.com";

		UserProfile profile = new UserProfile();

		return ResponseEntity.ok(profile);
public class UserProfile
	private String name;
	private String email;

	//Setters and getters

	public String toString() {
		return "UserProfile [name=" + name + ", email=" + email + "]";

5. Demo

We have an API http://localhost:8080/api/users/me, which we can access by directly putting username/password in the login form, but the third-party applications cannot access the API as we do in browsers. They need an oauth2 token.

5.1. Getting Authorization Grant Code from User

As shown in the above sequence diagram, the first step is to get an authorization grant from the resource owner from URL : http://localhost:8080/oauth/authorize?client_id=clientapp&response_type=code&scope=read_profile_info

It will bring a login page. Provide a username and password. For this demo, use “humptydumpty” and “123456”.

Login page
Login page

After login, you will be redirected to the grant access page where you choose to give access to third-party applications.

Get authorization grant
Get authorization grant

It will redirect to a URL like : http://localhost:8081/login?code=EAR76A. Here 'EAR76A' is authorization code for the third-party application.

5.2. Getting Access Token from Authorization Server

Now the application will use an authorization grant to get the access token. Here we need to make the following request. Use the code obtained in the first step here.



Content-Type: application/x-www-form-urlencoded
authorization: Basic Y2xpZW50YXBwOjEyMzQ1Ng==

Form data - application/x-www-form-urlencoded:


It will ask for client app credentials in a separate window.

Client auth
Client auth

Or make a similar request from cURL.

curl -X POST --user clientapp:123456 http://localhost:8081/oauth/token
		-H "content-type: application/x-www-form-urlencoded"
		-d "code=FfrzTj&grant_type=authorization_code&redirect_uri=http%3A%2F%2Flocalhost%3A8082%2Flogin&scope=read_user_info"
	"access_token": "59ddb16b-6943-42f5-8e2f-3acb23f8e3c1",
	"token_type": "bearer",
	"refresh_token": "cea0aa8f-f732-44fc-8ba3-5e868d94af64",
	"expires_in": 4815,
	"scope": "read_profile_info"

Read More : How to execute cURL commands in windows

5.3. Accessing User Data from Resource Server

Once we have the access token, we can go to the resource server to fetch protected user data.

Hit the following request:

curl -X GET http://localhost:8080/api/users/me
	 -H "authorization: Bearer 59ddb16b-6943-42f5-8e2f-3acb23f8e3c1"

It will return the response.


6. Dependencies

The pom file used for this spring security 5 oauth2 example is:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
        <relativePath /> <!-- lookup parent from repository -->
    <description>Demo project for Spring Boot</description>

Drop me your questions in the comments.

Happy Learning !!

Sourcecode Download


Notify of
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode