SpringBoot: API Authentication Using OAuth2 With Google

George Berar
Geek Culture
Published in
6 min readJan 15, 2022

Preventing unwanted access to sensitive data is critical when we talk about designing and exposing REST APIs so in today’s article I will give you a practical example on how to implement authentication by leveraging Google’s OAuth2 support.

Photo by Matthew Henry on Unsplash

Before we start you can find the entire code here.

As a side note I apologize for the small dimensions of the GIFs related to Google Cloud Console steps (in repo are bigger) but it seems this is the only way to achieve the same outcome on browser and mobile (on my iPhone the Medium app was crashing).

Ok, let’s dive in!

Background

When it comes to securing an API we talk mainly about authentication and authorization which usually go hand in hand. While there are as many proprietary methods as there are systems which utilize them, they are largely variations of a few major approaches and one of them is OAuth2 (or OAuth 2.0).

What is OAuth2?

Long story short it’s a standard designed to allow a website or application to access resources hosted by other web applications on behalf of a user. It provides consented access and restricts actions of what the client application can perform on resources on behalf of the user, without ever sharing the user’s credentials. A simplified OAuth2 flow looks like this:

OAuth2 flow as pictured by Okta Developer Blog

You can check this link to find out more on OAuth2.

Currently tech giants like Google, Facebook or Twitter are providing Authorization Servers and you can implement authentication and everything related to identifying personal accounts against their user database without the need to store and manage those details on your own.

You’ve probably seen something like this at some point:

Fiverr’s login pop-up

But what it’s happening behind the scenes?

If you sign in with Google for example, the web application will redirect you to Google’s login page where you need to provide your Google account credentials (in case you are not already logged in). If the credentials are correct you will be redirected back to the web application which receives an access token. The web application will send this access token to its backend on each request and the backend will validate it against Google to ensure it was not altered along the way or is not expired.

The Problem

Let’s suppose we build a web application where users can track their monthly expenses by uploading photos of their receipts. We want to allow our users to sign in using their Google account and we want to make sure our backend API is able to handle the authentication by validating the access tokens on each request.

How can we build our backend API to validate the tokens against Google?

The Solution

The solution implies leveraging the Google’s OAuth2 support. If you remember in the OAuth2 flow diagram we have an Authorization Server and a Resource Server. In our case Google will be the Authorization Server responsible of handling user authentication and generating access tokens and our backend will be the Resource Server responsible of validating the access tokens against Google and allowing our users to create, read, update or delete their monthly receipts.

Step 1. Configure Google OAuth2

1.1 Create New Project

In Google Cloud Console we create a new project:

1.2 Configure Consent Screen

Next we need to configure the consent screen by selecting our newly created project from the dropdown and clicking on OAuth consent screen.

We select External for User Type section because we want to work with Google accounts which are not necessarily part of an organization.

The App Information section is not really relevant but there you can specify the app name, maybe upload a logo and other details.

1.3 Set Scopes

For our use case the only scopes we need are: openid, email and profile.

Important Note: We added openid as scope because we want to use the thin layer that sits on top of OAuth2. This layer is called OpenID Connect and adds login and profile information about the person who is currently logged in. I will not go into more details since we are still in the OAuth2 context but you can find more on this topic here and here.

1.4 Set Test Users

Initially we want to check if our backend is able to work with a set of dummy users before handling real customers so we need to add the so called Test users.

For simplicity I’m adding my Google account used mainly for development purposes but you can add whatever Google account(s) you want to test with, as long as you know the credentials of course.

1.5 Create OAuth Client

For creating the OAuth Client we select Credentials from left panel and click CREATE CREDENTIALS.

OAuth client ID is used as credential type and Web application as application type.

Note: a pop-up will be displayed at the end containing the client id and secret. Copy these values and don’t share with anyone else.

1.6 Postman As Frontend

Because our focus is on the backend side ignoring completely the frontend part, we need a way of simulating the Google login and obtaining a valid access token. To do so we’ll use Postman and we need to do some minor adjustments to our OAuth Client.

We select Credentials from left panel and open our newly created client from OAuth 2.0 Client IDs table.

We add https://www.getpostman.com/oauth2/callback as Authorized redirect URIs and click SAVE.

Add correct authorized redirect URI for Postman callback

Step 2. Create Resource Server

In this step we configure our backend to act as a Resource Server.

2.1 Add Maven Dependency

The next Maven dependency is added in pom.xml:

2.2 Configure Application Properties

The next configurations are added in application.yml file under resources folder:

Configuring application properties

You will need to replace the <YOUR_CLIENT_ID> and <YOUR_CLIENT_SECRET> placeholders with your own client id and secret.

The same properties should be available if you work with application.properties instead of YAML files.

2.3 Configure Spring Security

The last thing we need to do is configuring Spring Security to act as a Resource Server:

Spring Security configuration

Step 3. Testing

To be able to generate access tokens from Postman we need to configure it in order to work with our OAuth Client.

Open Postman > New Request > Authorization > Select OAuth 2.0

Configuring Postman

We put https://www.getpostman.com/oauth2/callback as Callback URL and our correct client id and secret.

Clicking Get New Access Token button should open a pop-up where we need to provide the credentials for one of our test users. If the credentials are valid we should see something like:

The value of id_token should be copied because this is the generated access token we need.

Next, we try to execute a request against one of our backend endpoints without this token to see what happens:

Request without token

As you can see we get back 401 as expected because we didn’t provide an Authorization header with our token.

Adding the token to our request as Bearer Token gives us the expected output:

Request with token as value for Authorization header

That’s it!

Conclusion

As always please keep in mind this approach might or might not suit your project context or needs and I’m not in the position to say there’s no other way to do it differently or better. I really hope you enjoyed it and had fun reading it.

Stay safe and remember you can find the code here.

--

--

George Berar
Geek Culture

Senior Software Engineer • Freelancer • Tech Enthusiast