How to Secure REST Endpoint Using Spring Boot and OAuth2


Sharing is caring!

Overview

In this article, I will provide a simple example to secure REST example by using Oauth2. I will not explain what Oauth2 protocol is all about in detail. In short, to implement this authorization framework, we need:

  • Authorization Server
  • Resource Server
  • Client
  • Resource Owner

I found this link is one of the best explanation regarding OAuth2 framework.

Use Case

I will create a simple OAuth2 authorization framework using spring-boot 2.1.x. The authorization server will have two scopes, which are READ and WRITE. It has 4 grant types, but for the rest I just use two types, which are PASSWORD and REFRESH TOKEN. And for the token itself, I will use JWT token.

All the source code are available in my github repository.

Step 1: Authorization Server

AuthorizationServer.java

OAuth2SecurityInMemoryConfiguration.java

IssueAtTokenEnhancer.java

 

Step 2: Resource Server

In this resoruce server, I created two parts. One part is for resource server configuration, another part is for creating REST endpoint.

application.yml

ResourceServerConfig.java

HelloController.java

 

Run It

Retrieve Access Token

Make a POST request into url /oauth/token with Basic Authorization. Fill username with your CLIENT name and password with your SECRET value. Those values are configured in AuthorizationServer.java. The content-type must be application/x-www-form-urlencoded.

Setting HTTP Basic Auth
Grant type, username and password
Response

Request to Resource Server

All the requests to resource server require parameter access_token as part of the request.

Accessing insecure URL without any authorization.
Access endpoint for user who has role USER and scope READ.
Accessing endpoint for user who has role USER and scope TRUST. Since my authorization server does not have TRUST scope, so the request is denied.

Refresh Token

Just like retrieving access token, basic authorization must be set first with client and secret values. Then making a POST request with grant type refresh_token.

Refresh token

That’s All

Short posting for this one. Hope you enjoy it.

 

Author: ru rocker

I am a professional software developer with more than 10 years experiences. I am a certified Java Developer (SCJP and SCWCD). However, In the recent months, I have more interest in DevOps and start to become a polyglot developer. Python and Go-lang become my favorite programming languages besides Java.

Leave a Reply

Your email address will not be published. Required fields are marked *