Android:GoogleIdTokenVerifier.Builder中的transport和jsonFactory是什么?

61
在下面的代码中,transportjsonFactory是什么?(我不理解)

https://developers.google.com/identity/sign-in/android/backend-auth#using-a-google-api-client-library

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;

...

GoogleIdTokenVerifier verifier = new GoogleIdTokenVerifier.Builder(transport /**Here**/, jsonFactory /**Here**/)
.setAudience(Arrays.asList(CLIENT_ID))
// If you retrieved the token on Android using the Play Services 8.3 API or newer, set
// the issuer to "https://accounts.google.com". Otherwise, set the issuer to 
// "accounts.google.com". If you need to verify tokens from multiple sources, build
// a GoogleIdTokenVerifier for each issuer and try them both.
.setIssuer("https://accounts.google.com")
.build();

// (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.");
}
4个回答

59

由于所有其他答案都是废话,这里给出一个简短的答案:

import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.gson.GsonFactory;

GoogleIdTokenVerifier verifier =
    new GoogleIdTokenVerifier.Builder(new NetHttpTransport(), new GsonFactory());

4
注意,在最新版本的库中,JacksonFactory已被移除,请改用new GsonFactory()import com.google.api.client.json.gson.GsonFactory - Marax
3
这一定是我最喜欢的Stack Overflow答案,@Stevey。 - Nathan Dunn
1
这对我有用。非常好的答案:简短而直接。谢谢@Stevey。 - daniel rubambura

30
GoogleIdTokenVerifier.Builder返回一个GoogleIdTokenVerifier,该验证器将使用您提供的传输协议tokeninfo端点发出请求,并使用JSONFactory创建解析器以解析响应。以下是使用GoogleIdTokenVerifier.Builder的Cloud Endpoints项目的身份验证示例。
public class GoogleAuthenticator implements Authenticator {

    private static final Logger log = Logger.getLogger(GoogleAuthenticator.class.getName());
    private static final JacksonFactory jacksonFactory = new JacksonFactory();

    // From: https://developers.google.com/identity/sign-in/android/backend-auth#using-a-google-api-client-library
    // If you retrieved the token on Android using the Play Services 8.3 API or newer, set
    // the issuer to "https://accounts.google.com". Otherwise, set the issuer to
    // "accounts.google.com". If you need to verify tokens from multiple sources, build
    // a GoogleIdTokenVerifier for each issuer and try them both.

    GoogleIdTokenVerifier verifierForNewAndroidClients = new GoogleIdTokenVerifier.Builder(UrlFetchTransport.getDefaultInstance(), jacksonFactory)
            .setAudience(Arrays.asList(CRLConstants.IOS_CLIENT_ID, CRLConstants.ANDROID_CLIENT_ID_RELEASE, CRLConstants.ANDROID_CLIENT_ID_DEBUG))
            .setIssuer("https://accounts.google.com")
            .build();

    GoogleIdTokenVerifier verifierForOtherClients = new GoogleIdTokenVerifier.Builder(UrlFetchTransport.getDefaultInstance(), jacksonFactory)
            .setAudience(Arrays.asList(CRLConstants.IOS_CLIENT_ID, CRLConstants.ANDROID_CLIENT_ID_RELEASE, CRLConstants.ANDROID_CLIENT_ID_DEBUG))
            .setIssuer("accounts.google.com")
            .build();

    // Custom Authenticator class for authenticating google accounts
    @Override
    public User authenticate(HttpServletRequest request) {

        String token = request.getHeader("google_id_token");
        if (token != null) {

            GoogleIdToken idToken = null;
            try {
                idToken = verifierForNewAndroidClients.verify(token);
                if(idToken == null) idToken = verifierForOtherClients.verify(token);

                if (idToken != null) {

                    GoogleIdToken.Payload payload = idToken.getPayload();

                    // Get profile information from payload
                    String userId = payload.getSubject();
                    String email = payload.getEmail();

                    return new GoogleUser(userId, email);

                } else {
                    log.warning("Invalid Google ID token.");
                }

            } catch (GeneralSecurityException e) {
                log.warning(e.getLocalizedMessage());
            } catch (IOException e) {
                log.warning(e.getLocalizedMessage());
            }

        }

        return null;
    }

}

认证器接口目前不是Spring Security的一部分吗?我无法导入它。 - user4739287

5
你需要根据运行代码的平台选择传输方式。
引用文档内容:
Implementation is thread-safe, and sub-classes must be thread-safe. For maximum efficiency, applications should use a single globally-shared instance of the HTTP transport.

The recommended concrete implementation HTTP transport library to use depends on what environment you are running in:

Google App Engine: use com.google.api.client.extensions.appengine.http.UrlFetchTransport.
com.google.api.client.apache.ApacheHttpTransport doesn't work on App Engine because the Apache HTTP Client opens its own sockets (though in theory there are ways to hack it to work on App Engine that might work).
com.google.api.client.javanet.NetHttpTransport is discouraged due to a bug in the App Engine SDK itself in how it parses HTTP headers in the response.
Android:
For maximum backwards compatibility with older SDK's use newCompatibleTransport from com.google.api.client.extensions.android.http.AndroidHttp (read its JavaDoc for details).
If your application is targeting Gingerbread (SDK 2.3) or higher, simply use com.google.api.client.javanet.NetHttpTransport.
Other Java environments
com.google.api.client.javanet.NetHttpTransport is based on the HttpURLConnection built into the Java SDK, so it is normally the preferred choice.
com.google.api.client.apache.ApacheHttpTransport is a good choice for users of the Apache HTTP Client, especially if you need some of the configuration options available in that library.

文档链接:https://developers.google.com/api-client-library/java/google-http-java-client/reference/1.19.0/com/google/api/client/http/HttpTransport?is-external=true 如果您盲目地遵循第二个答案,您将会收到异常信息Caused by: java.lang.ClassNotFoundException: com.google.appengine.api.urlfetch.HTTPMethod。请注意!

2

JacksonFactory已被弃用。因此,这个可以使用。

import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.gson.GsonFactory;

GoogleIdTokenVerifier verifier = new GoogleIdTokenVerifier.Builder(new NetHttpTransport(), new GsonFactory())
.setAudience(Arrays.asList(CRLConstants.IOS_CLIENT_ID, CRLConstants.ANDROID_CLIENT_ID_RELEASE, CRLConstants.ANDROID_CLIENT_ID_DEBUG))
            .setIssuer("accounts.google.com")
            .build();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接