How to protect your Spring Boot microservice with OAuth2?

Protecting your microservice developed in Spring Boot is quite forward.

Spring does all the major work for you.

Here are the steps to follow:

STEP 1: Add spring boot starter oauth2 resource server dependency

STEP 2: Configure Authorization Server

STEP 3: Test

STEP 1: Add spring boot starter oauth2 resource server dependency

Add the below dependency in your project:

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

STEP 2: Configure Authorization Server

Add Authorization Server in application.yml file.

This is the “issuer” url you get while configuring your authorization server.

To know how to set up authorization server check here

Here is the entry I added while testing:

spring:
  security:
    oauth2:
      resourceserver:
        jwt:
          issuer-uri: http://localhost:8080/realms/myrealm

That’s it!

Quite straightforward and easy.

Now let’s test it.

Advertisements

STEP 3: Test

To test, let’s first create a Rest Controller:

package app.example;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {

	
	@GetMapping("/test")
	public String test() {
		
		return "success";
	}
}

Just a simple REST API which returns a string.

This will be automatically protected by Spring behind the screens!

Just adding the configuration and the resource server dependency will do the magic for you.

Let’s test it through postman.

You need to generate an access token by passing the client credentials you set up in authorization server ,before hitting the test API.

You can refer step 5 in this post to know how to set up a client in authorization server. Get the client credentials of the client thus created.

You can get the credentials from “Credentials” tab in KeyCloak:

You need to choose Authorization Type as OAuth2.

My client id is “myclient” and client secret is shown above.

You also need Access token URL which you can get from your authorization server (Refer step 6 in this post)

Let me try getting an access token using these credentials:

I ran the server on port 8085 as I was running the authorization server (keycloak) on port 8080.

Now let me hit the server using the access token just generated:

That’s it!

We protected a microservice with OAuth2 in two simple steps!

Here is the github link:

https://github.com/vijaysrj/keycloakresourceserver

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s