Home - Blog - Google - OAuth2 + JWT + Gmail letters

OAuth2 + JWT + Gmail letters

16.05.2024

40

IT news
blog

We will use Google Oauth2 for the oauth2 + JWT connection, but you can use any other provider

First, go to https://console.cloud.google.com/

Let’s create the project, if it hasn’t been created yet, then go to APIs and services -> credentials and create new OAuth client ID credentials, as shown in the screenshots:

 

 

After that, we have the Client ID and Client secret, which we will need in application.yml, which we will create later.

Also, to work with letters in the mail, we need to add the Gmail API, for this, we go to the API Library, search for Gmail there, and see the result:

 

 

Go to the Gmail API and click Enable, the following result should appear:

 

 

The next thing to do is to create Spring Boot with all the necessary dependencies, in our case it is:

 

 

To begin, let’s create a simple user that will be authorized and stored in the database, as well as the corresponding repository using Spring Data JPA:

 

 

We create public and private keys, which we will need later to decode and verify the JWT.

To do this, execute these commands in the resources/certs directory:

openssl genrsa -out keypair.pem 2048

openssl rsa -in keypair.pem -pubout -out publicKey.pem

openssl pkcs8 -topk8 -inform PEM -outform PEM -nocrypt -in keypair.pem -out privateKey.pem

And as you can see, our keys are created and we get approximately the following result:

 

 

Now let’s create a record that will represent these values:

 

 

Let’s create JwtUtils, which will check the validity of the token:

 

 

Also, let’s add JwtAccessTokenFilter together with TokenType:

 

 

Now let’s configure SecurityConfig:

 

 

Now let’s create a JwtGenerator:

 

 

Now let’s create application.yml with the following content:

 

 

Let’s create AuthService, as well as AuthResponseDto and EmailDto:

 

 

Now let’s create an AuthController:

 

 

This controller returns a view ‘user’, which we also need to create:

 

 

This HTML file should be located in the following path:

 

 

Now let’s add another controller with secure endpoints, which we will make requests with JWT:

 

 

We launch the application, go to the browser, and follow the localhost:8080/login link, and we are immediately redirected to the authorization page through Google:

 

 

After authorization, we get approximately the following result:

 

 

Here you can see that we have received all emails from Google and received an access token that we can use to send requests to our secure endpoints, for this we will use Postman and try to send a request to http://localhost:8080/api/welcome-message:

 

 

So we made a service that authenticates through Google and returns an internal JWT that can be used to send requests to our endpoints.