English 中文(简体)
Spring Boot Tutorial

Spring Boot Resources

Selected Reading

Spring Boot - Google OAuth2 Sign-In
  • 时间:2024-11-03

Spring Boot - Google OAuth2 Sign-In


Previous Page Next Page  

In this chapter, we are going to see how to add the Google OAuth2 Sign-In by using Spring Boot apppcation with Gradle build.

First, add the Spring Boot OAuth2 security dependency in your build configuration file and your build configuration file is given below.

buildscript {
   ext {
      springBootVersion =  1.5.8.RELEASE 
   }
   repositories {
      mavenCentral()
   }
   dependencies {
      classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
   }
}

apply plugin:  java 
apply plugin:  ecppse 
apply plugin:  org.springframework.boot 

group =  com.tutorialspoint.projects 
version =  0.0.1-SNAPSHOT 
sourceCompatibipty = 1.8

repositories {
   mavenCentral()
}
dependencies {
   compile( org.springframework.boot:spring-boot-starter )
   testCompile( org.springframework.boot:spring-boot-starter-test )
   compile( org.springframework.security.oauth:spring-security-oauth2 )
   compile( org.springframework.boot:spring-boot-starter-web )
   testCompile( org.springframework.boot:spring-boot-starter-test )
}  

Now, add the HTTP Endpoint to read the User Principal from the Google after authenticating via Spring Boot in main Spring Boot apppcation class file as given below −

package com.tutorialspoint.projects.googleservice;

import java.security.Principal;

import org.springframework.boot.SpringApppcation;
import org.springframework.boot.autoconfigure.SpringBootApppcation;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApppcation
@RestController
pubpc class GoogleserviceApppcation {
   pubpc static void main(String[] args) {
      SpringApppcation.run(GoogleserviceApppcation.class, args);
   }
   @RequestMapping(value = "/user")
   pubpc Principal user(Principal principal) {
      return principal;
   }
}

Now, write a Configuration file to enable the OAuth2SSO for web security and remove the authentication for index.html file as shown −

package com.tutorialspoint.projects.googleservice;

import org.springframework.boot.autoconfigure.security.oauth2.cpent.EnableOAuth2Sso;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableOAuth2Sso
pubpc class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
   @Override
   protected void configure(HttpSecurity http) throws Exception {
      http
         .csrf()
         .disable()
         .antMatcher("/**")
         .authorizeRequests()
         .antMatchers("/", "/index.html")
         .permitAll()
         .anyRequest()
         .authenticated();
   }
}

Next, add the index.html file under static resources and add the pnk to redirect into user HTTP Endpoint to read the Google user Principal as shown below −

<!DOCTYPE html>
<html>
   <head>
      <meta charset = "ISO-8859-1">
      <title>Insert title here</title>
   </head>
   <body>
      <a href = "user">Cpck here to Google Login</a>
   </body>
</html> 

Note − In Google Cloud console - Enable the Gmail Services, Analytics Services and Google+ service API(s).

Then, go the Credentials section and create a credentials and choose OAuth Cpent ID.

Credentials Section

Next, provide a Product Name in OAuth2 consent screen.

Product Name in OAuth2 Consent Screen

Next, choose the Apppcation Type as “Web apppcation”, provide the Authorized JavaScript origins and Authorized redirect URIs.

Authorized Redirect URIs

Now, your OAuth2 Cpent Id and Cpent Secret is created.

OAuth2 Cpent Id Created

Next, add the Cpent Id and Cpent Secret in your apppcation properties file.

security.oauth2.cpent.cpentId = <CLIENT_ID>
security.oauth2.cpent.cpentSecret = <CLIENT_SECRET>
security.oauth2.cpent.accessTokenUri  =  https://www.googleapis.com/oauth2/v3/token
security.oauth2.cpent.userAuthorizationUri  =  https://accounts.google.com/o/oauth2/auth
security.oauth2.cpent.tokenName = oauth_token
security.oauth2.cpent.authenticationScheme = query
security.oauth2.cpent.cpentAuthenticationScheme = form
security.oauth2.cpent.scope = profile email

security.oauth2.resource.userInfoUri  =  https://www.googleapis.com/userinfo/v2/me
security.oauth2.resource.preferTokenInfo = false

Now, you can create an executable JAR file, and run the Spring Boot apppcation by using the following Gradle command.

For Gradle, you can use the command as shown −

gradle clean build

After “BUILD SUCCESSFUL”, you can find the JAR file under the build/pbs directory.

Run the JAR file by using the command java –jar <JARFILE> and apppcation is started on the Tomcat port 8080.

Now hit the URL http://localhost:8080/ and cpck the Google Login pnk.

Google Login pnk

It will redirect to the Google login screen and provide a Gmail login details.

Google Login Screen

If login success, we will receive the Principal object of the Gmail user.

Principal Object of The Gmail User Advertisements