Spring Security Oauth2: Google Login
In this post, learn about implementing spring security oauth2 and authenticating your users using the Google authorization service.
Join the DZone community and get the full member experience.
Join For FreeIntroduction
With the evolution of technologies, we also need to take care of security for our web applications. In this post, we're going to talk about one of the ways to secure your spring boot applications using spring-security-oauth2. I will demonstrate how we can authenticate the user with their Google accounts using the oauth2 stack in spring security 5.
Getting Started
We will first create our project and make sure your Pom.xml should at least have the dependencies that I have below.
xxxxxxxxxx
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
I have used the spring boot starter oauth2 client for this article, but now everything is there in spring security 5, and we can use the OAuth support within spring security.
Configuring Your Application
The first thing that you need to do is you will need to create your application in Google console to tell Google that I have an application that will be using your authorization services.
Visit Google API Console and sign in with your Google account if you are not signed in. You need to go to credentials tab -> Create Credentials -> Oauth2 ClientID .
It will then ask you to select what type of application you're going to build. Select web application -> Application Name. You can set up a redirect URI if you want(Please make sure if you're configuring a redirect URI in google console then you will also need to include that in spring-boot configuration).
Once you've entered the details, click on create an application. It will give you some alphanumeric ClientID and Client-Secret.
Configuring Your Spring Boot Application
Once you've set up your ClientID and Client-Secret from Google, we're good to continue integrating this with our spring-boot application. You now just need to add a few properties in your spring boot application as shown below.
x
spring:
security:
oauth2:
client:
registration:
google:
client-id: your-client-ID.apps.googleusercontent.com
client-secret: Your-Client-Secret-Key
redirect-uri: Redirect-Uri that you've configured
Run your application and go to the server address, and try to access an endpoint. It will redirect you to the Google login page, and after logging in, you will be able to access protected resources. The code is available on the github-repository. With that being said, thank you so much for taking the time to read this article. I hope this will help you in some way.
Opinions expressed by DZone contributors are their own.
Comments