Share
Gmail API and Google Calendar API  – Spring Boot and OAuth2

Gmail API and Google Calendar API – Spring Boot and OAuth2

Demo Project for Gmail API and Google Calendar API Using Spring Boot Rest API with OAuth2

In this page, I’ll walk through the Demo Project for Gmail API and Google Calendar API Using Spring Boot with OAuth2.

This post shows you how to build a sample web application doing various things with Google APIs using OAuth2 and Spring Boot. It starts with a simple, single-provider single-sign on, and works up to a self-hosted OAuth2 Authorization Server with a choice of authentication providers (Fitbit or Facebook or Github).

The samples are all single-page apps using Spring Boot and Spring OAuth on the back end. They also all use AngularJS on the front end, but the changes needed to convert to a different JavaScript framework or to use server side rendering would be minimal.

Find the source code for Gmail API With OAuth2 in GitHub

Find the source code for Google Calendar API With OAuth2 in GitHub

Gmail API and Google Calendar API – Spring Boot and OAuth2

This project implemented with below skills.

1) Spring Boot
2) Rest API
3) Google Gmail API
4) Google Calendar API
5) OAuth2

What do I do?

I am simple Spring Boot application which secured by Spring Security. Instead of using simple form based security, I am secured by Spring Security OAuth2 and the OAuth provider is Google.

Why am I required?

Developing a Spring Boot web application with Security enabled and integrated with Google is hard to implement. So this is a sample implementation of Spring Boot + Spring Security OAuth2 + Google API Provider.

The project is built with Maven so you can run the build using mvn clean build

The application.properties (in src/main/resources) contains the details of the Google application which it uses to authenticate details. Change the values of the following attributes to the values for your application google.client.id google.client.secret and etc.,

To register a Google App perform the following steps

Go to https://console.developers.google.com and login with your Google account (this will be the developer account and the email of this account will be published when someone tries to authenticate with the Google application)

If you don’t have a project create a new one and then click into the project.

In the menu on the left side select “APIs & auth” –> “Credentials” –> “Create a new client ID”

In the popup select the following

Application Type = SpringBoot Web Application

Authorized Javascript Origins = ,

Authorized Redirect URI = , the URI for our application is http://localhost:9000/login/google and http://localhost:9000/login/gmailCallback on different lines.

Copy the client ID and client Secret and update the application.properties

Make sure you update the mandatory values on the “APIs & auth” –> “Consent screen” page as the application will not work without it.

When you have a the Google App configured and the Spring boot application and you navigate to http://localhost:9000/login/google or http://localhost:9000/login/gmail. It will redirect you to a Google login page.

Upon login it will ask you to authorize your application for access to your account to get email and profile data. On successful login it will render the basic HTML page which means the authentication was sucessful.

<!– Google Calendar API Maven Dependency–>

<dependency>

<groupId>com.google.apis</groupId>

<artifactId>google-api-services-calendar</artifactId>

<version>v3-rev224-1.22.0</version>

</dependency>

<!– Gmail API Maven Dependency–>

<dependency>

<groupId>com.google.apis</groupId>

<artifactId>google-api-services-gmail</artifactId>

<version>v1-rev65-1.18.0-rc</version>

</dependency>

That’s it. Thank you for reading this post.

I want you to do something for me right now: Leave a comment !!!

Like this post? Don’t forget to share it!

Enjoy!!!

Save

11 Comments on this Post

  1. DominikBethe

    I see your blog needs some fresh articles. Writing manually is time consuming, but there is solution for this hard task.
    Just search for; Miftolo’s tools rewriter

    Reply
  2. Sanket

    Hi. this is what i exactly need. However how can i go to google api and do further process? please send me a link if you have. Thanks

    Reply
  3. Sanket

    Hey i have got that credentials from google autorize api. now can you please explain how to check those emails and calendars from postman or any other platform?

    Reply
  4. kavyashreee

    i did sign-in gmail with my application, now i got the access token and fetch user details,but how to take user details into my controller…?

    Reply
  5. Hi Kavya,

    Use the below code:

    @RequestMapping(value = “/login/gmailDetails”, method = RequestMethod.GET, params = “code”)
    public ResponseEntity oauth2Callback(@RequestParam(value = “code”) String code) {
    JSONObject json = new JSONObject();
    JSONArray arr = new JSONArray();

    // String message;
    try {
    TokenResponse response = flow.newTokenRequest(code).setRedirectUri(redirectUri).execute();
    credential = flow.createAndStoreCredential(response, “userID”);

    client = new com.google.api.services.gmail.Gmail.Builder(httpTransport, JSON_FACTORY, credential)
    .setApplicationName(APPLICATION_NAME).build();
    String userId = “me”;
    String query = “subject:’Pay Bill'”;
    ListMessagesResponse MsgResponse = client.users().messages().list(userId).setQ(query).execute();

    List messages = new ArrayList();

    System.out.println(“message length:” + MsgResponse.getMessages().size());

    for (Message msg : MsgResponse.getMessages()) {

    messages.add(msg);

    Message message = client.users().messages().get(userId, msg.getId()).execute();
    System.out.println(“snippet :” + message.getSnippet());

    arr.put(message.getSnippet());

    }
    json.put(“response”, arr);

    for (Message msg : messages) {

    System.out.println(“msg: ” + msg.toPrettyString());
    }

    } catch (Exception e) {

    System.out.println(“exception cached “);
    e.printStackTrace();
    }

    return new ResponseEntity(json.toString(), HttpStatus.OK);
    }

    Reply
  6. Muhammad Shafaat

    Hey i have an error with this code, please help me
    2017-12-27 15:39:21.313 ERROR 1632 — [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Handler dispatch failed; nested exception is java.lang.NoSuchMethodError: com.google.api.client.auth.oauth2.AuthorizationCodeFlow$Builder.setScopes(Ljava/util/Collection;)Lcom/google/api/client/auth/oauth2/AuthorizationCodeFlow$Builder;] with root cause

    java.lang.NoSuchMethodError: com.google.api.client.auth.oauth2.AuthorizationCodeFlow$Builder.setScopes(Ljava/util/Collection;)Lcom/google/api/client/auth/oauth2/AuthorizationCodeFlow$Builder;

    Thanks

    Reply
    • Hey, Check your OAuth2 Credentials(Key and Secret Key) in your gmail account

      Reply
      • Muhammad Shafaat

        Thanks, its work
        but how i can access drive from api google drive, cause i have error at Drive.Builder, you can help me?

        Reply
      • Muhammad Shafaat

        Here my code
        import java.io.IOException;
        import java.util.ArrayList;
        import java.util.Collections;
        import java.util.List;

        import javax.servlet.http.HttpServletRequest;

        import org.json.JSONArray;
        import org.json.JSONObject;
        import org.springframework.beans.factory.annotation.Value;
        import org.springframework.http.HttpStatus;
        import org.springframework.http.ResponseEntity;
        import org.springframework.stereotype.Controller;
        import org.springframework.web.bind.annotation.RequestMapping;
        import org.springframework.web.bind.annotation.RequestMethod;
        import org.springframework.web.bind.annotation.RequestParam;
        import org.springframework.web.bind.annotation.RestController;
        import org.springframework.web.servlet.view.RedirectView;

        import com.google.api.client.auth.oauth2.AuthorizationCodeRequestUrl;
        import com.google.api.client.auth.oauth2.Credential;
        import com.google.api.client.auth.oauth2.TokenResponse;
        import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
        import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
        import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets.Details;
        import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
        import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
        import com.google.api.client.http.HttpTransport;
        import com.google.api.client.json.JsonFactory;
        import com.google.api.client.json.jackson2.JacksonFactory;
        import com.google.api.services.drive.Drive;
        import com.google.api.services.drive.Drive.Files;
        import com.google.api.services.drive.DriveScopes;
        import com.google.api.services.drive.model.FileList;
        import com.google.api.services.drive.model.File;

        @Controller
        @RestController
        public class GoogleOauthController {

        private static final String APPLICATION_NAME = “oauth drive”;
        private static HttpTransport httpTransport;
        private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
        private static com.google.api.services.drive.Drive service;

        GoogleClientSecrets clientSecrets;
        GoogleAuthorizationCodeFlow flow;
        Credential credential;

        @Value(“${drive.client.clientId}”)
        private String clientId;

        @Value(“${drive.client.clientSecret}”)
        private String clientSecret;

        @Value(“${drive.client.redirectUri}”)
        private String redirectUri;

        @RequestMapping(value = “/login/drive”, method = RequestMethod.GET)
        public RedirectView googleConnectionStatus(HttpServletRequest request) throws Exception {
        return new RedirectView(authorize());
        }

        @RequestMapping(value = “/login/callbackoauth”, method = RequestMethod.GET, params = “code”)
        public List oauth2Callback(@RequestParam(value = “code”) String code) {

        // System.out.println(“code->” + code + ” userId->” + userId + ”
        // query->” + query);

        JSONObject json = new JSONObject();
        JSONArray arr = new JSONArray();

        List result = new ArrayList();

        // String message;
        try {
        TokenResponse response = flow.newTokenRequest(code).setRedirectUri(redirectUri).execute();
        credential = flow.createAndStoreCredential(response, “userID”);
        System.out.println(credential);
        service = new Drive.Builder(httpTransport, JSON_FACTORY, credential)
        .setApplicationName(APPLICATION_NAME).build();

        Files.List request = service.files().list();

        do {
        try {
        FileList files = request.execute();

        result.addAll(files.getItems());
        request.setPageToken(files.getNextPageToken());
        } catch (IOException e) {
        System.out.println(“An error occurred: ” + e);
        request.setPageToken(null);
        }
        } while (request.getPageToken() != null &&
        request.getPageToken().length() > 0);

        } catch (Exception e) {

        System.out.println(“exception cached “);
        e.printStackTrace();
        }

        return result;
        }

        private String authorize() throws Exception {
        AuthorizationCodeRequestUrl authorizationUrl;
        if (flow == null) {
        Details web = new Details();
        web.setClientId(clientId);
        web.setClientSecret(clientSecret);
        clientSecrets = new GoogleClientSecrets().setWeb(web);
        httpTransport = GoogleNetHttpTransport.newTrustedTransport();
        flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, JSON_FACTORY, clientSecrets,
        Collections.singleton(DriveScopes.DRIVE)).build();
        }
        authorizationUrl = flow.newAuthorizationUrl().setRedirectUri(redirectUri);

        System.out.println(“drive authorizationUrl ->” + authorizationUrl.build());
        return authorizationUrl.build();
        }
        }

        Reply
  7. Hey, I am sending emails using Google OAuth 2 + Spring boot + Spring JavaMail API starter. I am stuck with the token expiry and I want to handle auto-refresh of my token. Do you know any way how to handle auto-refresh of access token?

    Reply
  8. iam getting always MsgResponse.getMessages() null value is their any solution??

    Reply

Leave a Comment

*