Android用google登录,用服务器端java

时间:2017-07-16 21:24:33

标签: java android server

我正在使用google登录客户端(android)和服务器端(Java)。在android端,我获得了cliend id和访问令牌,但我需要验证访问令牌并获取用户信息服务器端,我按照这个链接https://developers.google.com/identity/sign-in/android/backend-auth但我无法理解流程。我也遇到语法错误"令牌上的语法错误"上        GoogleIdToken idToken = verifier.verify(idTokenString); idTokenString是从android端获得的字符串标记。

任何人都可以帮我解决这个问题,并了解流程。 这是我的代码:

  package com.secret.secret.utils;
  import java.io.IOException;
  import java.util.Collections;
  import java.util.logging.Logger;

  import javax.servlet.ServletException;
  import javax.servlet.http.HttpServletResponse;

  import org.apache.catalina.Authenticator;
  import org.apache.catalina.connector.Request;

  import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken;
  import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken.Payload;
  import com.google.api.client.googleapis.auth.oauth2.GoogleIdTokenVerifier;
  import com.google.api.client.http.HttpTransport;
  import com.google.api.client.json.JsonFactory;
  public class GoogleUtil  {


private HttpTransport transport;

private JsonFactory jsonFactory;
String clientId="My client Id";

GoogleIdTokenVerifier verifier = new GoogleIdTokenVerifier.Builder(transport, jsonFactory)
        .setAudience(Collections.singletonList(clientId))
        // Or, if multiple clients access the backend:
        //.setAudience(Arrays.asList(CLIENT_ID_1, CLIENT_ID_2, CLIENT_ID_3))
        .build();

private GoogleIdToken idTokenString;

    // (Receive idTokenString by HTTPS POST)

    GoogleIdToken idToken = verifier.verify(idTokenString);
    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();
      boolean emailVerified = Boolean.valueOf(payload.getEmailVerified());
      String name = (String) payload.get("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.");
    }

   }
  }

1 个答案:

答案 0 :(得分:0)

在你的Android客户端:

public void handleSigninResult(GoogleSignInResult signInResult){
    if (signInResult.isSuccess()){
        GoogleSignInAccount account = signInResult.getSignInAccount();
        String idToken = account.getIdToken();

        //use this idToken in your server-side verification
    }
}