7

我正在开发基于与服务器通信的 android 应用程序,并且我想使用 Google(g+) 身份验证机制。

基本上,我认为它应该像这样工作:

  1. 在我的 android 应用程序中,用户使用他的电子邮件和密码登录到 Google。
  2. 用户允许访问他的相关 Google 应用程序的数据。
  3. 成功登录后,我的 android 应用程序收到访问令牌。
  4. 在与我的服务器进一步通信时,我的 android 应用程序应该使用接收到的 Google 访问令牌(例如:在查询中)。
  5. 当我的服务器从 android 应用程序接收到一些带有访问令牌的查询时,它应该询问谷歌这个令牌是否有效(以及对谁有效),如果是,服务器应该假设用户已经通过谷歌的身份验证。

我的问题是:如果给定的访问令牌有效,服务器应该如何询问谷歌?我想我应该以某种方式检查令牌是否对我的 android 应用程序有效。

我已经尝试了许多对 Google API 的 Google 查询,但我发现这些查询都没有达到我的预期。你能给我举个例子吗?

4

2 回答 2

2

您可以验证是否access_token有效。

你需要发送GETapi 端点发送请求:https://www.googleapis.com/oauth2/v1/tokeninfo请求中包含您的 access_token。

你可以这样尝试:

 String connection = new ConnectionService().connectionGoogle("https://www.googleapis.com/oauth2/v1/tokeninfo", "access_token=" + "YOUR_EXISTING_ACCESS_TOKEN");
        System.out.println(connection);

上面代码中使用的方法是:

public static String connectionGoogle(String url, String parameter) throws MalformedURLException, ProtocolException, IOException {

        URL url1 = new URL(url);
        HttpURLConnection request1 = (HttpURLConnection) url1.openConnection();
        request1.setRequestMethod("GET");
        request1.setDoOutput(true);
        request1.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        OutputStreamWriter wr = new OutputStreamWriter(request1.getOutputStream());
        wr.write(parameter);
        wr.flush();
        request1.connect();
        String responseBody = convertStreamToString(request1.getInputStream());
        wr.close();
        return responseBody;
    }

    private static String convertStreamToString(InputStream is) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line).append("\n");
            }
        } catch (IOException e) {
        } finally {
            try {
                is.close();
            } catch (IOException e) {
            }
        }

        return sb.toString();
    }
于 2013-11-06T06:02:41.333 回答
0

您可以使用 tokeninfo 端点检查令牌(访问或 ID 令牌)。如果您只想使用 API,可以使用API Explorer 中的 TokenInfo API

您可以使用 Google 提供的 OAuth v2 库来执行 API 调用。

您还可以按照OAuth v2 Playground 文档中的说明形成 URL 并执行 GET 查询。

于 2013-10-29T21:19:37.653 回答