如何使用通过GoogleAuthUtil class获得的token获取用户信息?

How to use token obtained using GoogleAuthUtil class to get user information?

我正在构建一个 Android 应用程序,我想在其中使用 google 帐户对用户进行身份验证。我正在使用 GoogleAuthUtil class 从 google 获取令牌,如下所示

protected String fetchToken() throws IOException{
    try {
        return GoogleAuthUtil.getToken(act, email, scope);
    } catch (GoogleAuthException e) {
        e.printStackTrace();
    }
    return null;
}

这里,act是currentactivity,email是使用accountpicker和scope=audience:server:client_id:X得到的值,其中X是web应用的客户端ID。

我得到了一些很长的结果,比如 eyJhbGciOiJSUzI1NiIsImtpZCI6ImFhMTkwMjZlYTgwNjYxNjI4ZjdiYzM5OTgyNDczZTFlYTE0NTVhNWQifQ.eyJpc3MiOiJhY2Nvd...... 作为 ID 令牌,但我不知道如何使用这个 ID 令牌来检索用户信息。

请帮助我了解如何从 ID 令牌获取用户信息。

经过一些研究,我得到了关注。

ID token用于验证用户的真实性,access token用于获知用户即将登录的邮箱id信息。访问令牌的获取方式与id令牌相同,如下所示。

 oAuthscopes = "oauth2:"+"https://www.googleapis.com/auth/userinfo.email"+" "+"https://www.googleapis.com/auth/plus.login";

protected String fetchAccessToken() throws IOException{
    try {
        return GoogleAuthUtil.getToken(act, email, oAuthscopes);
    }
    catch(GooglePlayServicesAvailabilityException e){
        act.handleException(e);
    }
    catch(UserRecoverableAuthException e){
        act.handleException(e);
    }
    catch (GoogleAuthException e) {
        e.printStackTrace();
    }
    return null;
}

注意oAtuthScopes的值。您可以根据应用程序的需要使用 space 指定任意数量的范围,以请求用户的许可。

现在,要从这些范围获取用户信息,请执行以下操作。

URL url = new URL("https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token="+accessToken);
        StringBuffer val = returnJson(url);
url = new URL("https://www.googleapis.com/oauth2/v1/tokeninfo?alt=json&id_token="+idToken);
        StringBuffer valVerify = returnJson(url);

方法returnjSon(URL)是

StringBuffer returnJson(URL url) throws IOException {
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    InputStream iStream = conn.getInputStream();

    BufferedReader read = new BufferedReader(new InputStreamReader(iStream));

    String line;
    StringBuffer val = new StringBuffer();

    while((line = read.readLine())!=null){
        val.append(line);
    }

    return val;
}

访问令牌将return类似于

{ "id": "10271045940xxxxxx", "email": "xxxx", "verified_email":正确,"name":"XXXX","given_name":"XXXX", "family_name": "XXXX", "link": "https://plus.google.com/+XXXX", "picture": "https://lh4.googleusercontent.com/xxxx", "gender": "male", "locale": "XX"}

id 令牌将 return 类似的东西。您可以在 logcat 中打印出来进行预览。

然后,

        JSONObject reader = new JSONObject(val.toString());

        String email = (String)reader.get("email"));
        String name = (String)reader.get("name"));

        reader = new JSONObject(valVerify.toString());
        boolean verified = reader.getBoolean("email_verified"));