Google OAuth 2.0 Authentication In Java

Posted By : Vikash Kumar sahani | 03-May-2021

Google provides Google APIs client library, to access protected data stored in Google services, such as documents, sheets, images, etc, we have to use OAuth 2.0 authorization. Google APIs support OAuth 2.0 flows for various client applications. In all of these flows, the client application requests an access token that is associated with only your client application and the owner of the protected data being accessed. The access token is also linked with a limited scope that defines the type of data your client application has access to. A crucial objective for OAuth 2.0 is to offer convenient and secure access to the protected data while reducing the potential impact if an access token is stolen.

Steps to get OAuth client ID

  • Create a new project here
  • Go to the credential option, select create credential option and select OAuth client ID
  • Download that generated OAuth client ID in JSON format

Dependecies Required

Maven

    <dependency>
      <groupId>com.google.api-client</groupId>
      <artifactId>google-api-client</artifactId>
      <version>1.31.2</version>
    </dependency>

Gradle

     repositories {
       mavenCentral()
        google()
   }
    dependencies {
    compile 'com.google.api-client:google-api-client:1.31.2'
  } 

After downloading the OAuth client Id.json file paste that file into the resources folder of your project.

 

Now let's see how we can use the OAuth client Id.json file for authentication with the Google client library

     
  import java.io.InputStream;
  import java.io.InputStreamReader;
  import java.security.GeneralSecurityException;
  import java.util.ArrayList;
  import java.util.Arrays;
  import java.util.Collections;
  import java.util.List;
   
  import com.google.api.client.auth.oauth2.Credential;
  import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
  import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
  import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
  import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
  import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
  import com.google.api.client.json.jackson2.JacksonFactory;
   

         public class ClassName {

                 public String methodName() throws IOException, GeneralSecurityException{

                  InputStream is = ClassName.class.getResourceAsStream("/OAuth clinet Id.json");

                  GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JacksonFactory.getDefaultInstance(), new InputStreamReader(is));

                  List<String> scope = new ArrayList<>();

                  scope.add(SheetScopes.SHEET);

                  GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(GoogleNetHttpTransport.newTrustedTransport(), JacksonFactory.getDefaultInstance(),                                                                                                                                                                             clientSecrets,scope).setDataStoreFactory(new FileDataStoreFactory(new  java.io.File("tokens"))) 
                                                                                                                                       .setAccessType("offline").build();

                   LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(your port number).build();

                    Credential credential = new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");

                    System.out.println(credential);

                    return "success";

            }

}

Finally, we can use this credential to access the google client API library.

 

 

 

 

About Author

Author Image
Vikash Kumar sahani

He is Working as Java Developer and having good knowledge in Core Java, Spring Boot,, Hibernate.He is quick learner, and self motivated

Request for Proposal

Name is required

Comment is required

Sending message..