getting null pointer exception while using google api client on server side servlet

Viewed 313

so iam developing project which is basically a voting platform with google SignIn option. authenticating the users by their signed in google id.

here is the javascript file of index page(welcome page)

function onSuccess(googleUser) {
    var profile = googleUser.getBasicProfile();
    gapi.client.load('plus', 'v1', function () {
        var request = gapi.client.plus.people.get({
            'userId': 'me'
        });
    });
    var id_token = googleUser.getAuthResponse().id_token;
    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'https://index.jsp/tokensignin');
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.onload = function() {
      console.log('Signed in as: ' + xhr.responseText);
    };
    xhr.send('idtoken=' + id_token);

    redirect();
}

function redirect(){
    window.location="submit.jsp";
}

function onFailure(error) {
    alert('signIn failed');
}

function renderButton() {
    gapi.signin2.render('gSignIn', {
        'scope': 'profile email',
        'width': 150,
        'height': 30,
        'longtitle': true,
        'theme': 'dark',
        'onsuccess': onSuccess,
        'onfailure': onFailure
    });
}

function signOut() {
    var auth2 = gapi.auth2.getAuthInstance();
    auth2.signOut().then(function () {
        console.log('User signed out.');
    });
}

After the index page loads with this script iam expecting to reacive id_token on server side servlet. the servlet and xml configuration are below:

<?xml version="1.0" encoding="UTF-8"?>
<web-app >
  <display-name>vooting_proj</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <servlet-name>subvote</servlet-name>
    <servlet-class>vooting_proj.VoteSer</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>subvote</servlet-name>
    <url-pattern>/index.jsp</url-pattern>
  </servlet-mapping>

  <servlet-mapping>
    <servlet-name>subvote</servlet-name>
    <url-pattern>/submit.jsp</url-pattern>
  </servlet-mapping>
</web-app>

servlet:

public class VoteSer extends HttpServlet {

    private static final JsonFactory JSON_FACTORY = new JacksonFactory();
    private static final String CLIENT_ID ="1067440508780-4sohls7be8loq4fc61g54pp4211j63h8.apps.googleusercontent.com";

    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        GoogleIdTokenVerifier verifier = new GoogleIdTokenVerifier.Builder(new NetHttpTransport(), JSON_FACTORY)
                .setAudience(Collections.singletonList(CLIENT_ID))
                // Or, if multiple clients access the backend:
                //.setAudience(Arrays.asList(CLIENT_ID_1, CLIENT_ID_2, CLIENT_ID_3))
                .build();

        String idTokenString= request.getParameter("idtoken");

        GoogleIdToken idToken= null;
        try {
            idToken = verifier.verify(idTokenString);
        } catch (GeneralSecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        if (idToken != null) {
            Payload payload = idToken.getPayload();

            // Print user identifier
            String userId = payload.getSubject();
            System.out.println("User ID: " + userId);

            // Get profile information from payload
            String email = payload.getEmail();
            System.out.println(email);
            boolean emailVerified = Boolean.valueOf(payload.getEmailVerified());
            String name = (String) payload.get("name");
            System.out.println(name);
            String pictureUrl = (String) payload.get("picture");
            String locale = (String) payload.get("locale");
            String familyName = (String) payload.get("family_name");
            String givenName = (String) payload.get("given_name");

            // Use or store profile information
            // ...

        } else {
            System.out.println("Invalid ID token.");
        }

        String sub=request.getParameter("vote_sub");
        System.out.println(sub);

    }

}

so when iam running the above code, getting null pointer exception in these classes:

com.google.api.client.googleapis.auth.oauth2.GoogleIdToken;
com.google.api.client.googleapis.auth.oauth2.GoogleIdToken.Payload;
com.google.api.client.googleapis.auth.oauth2.GoogleIdTokenVerifier; 

elcips is asking me to enclose this part in try-catch block:

GoogleIdToken idToken= null;
        try {
            idToken = verifier.verify(idTokenString);
        } catch (GeneralSecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

when iam not handling this, its giving me exception at run time

unhandled Exception GeneralSecurityException

please help with this problem, as this my first project i eagerly want complete.

0 Answers
Related