【问题标题】:Connection with Oauth 2.0 Google Calendar与 Oauth 2.0 谷歌日历连接
【发布时间】:2012-06-05 02:39:25
【问题描述】:
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpResponseException;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson.JacksonFactory;
import com.google.api.client.util.DateTime;
//import com.google.api.services.calendar.Calendar;
import com.google.api.services.calendar.model.Calendar;
import com.google.api.services.calendar.model.Event;
import com.google.api.services.calendar.model.EventAttendee;
import com.google.api.services.calendar.model.EventDateTime;
import com.google.api.client.googleapis.services.GoogleClient.Builder;
//import com.google.api.services.calendar.Calendar.Calendars;
//import com.google.api.services.calendar.Calendar.Calendars.Insert;
import com.google.api.client.auth.oauth2.AuthorizationCodeFlow;
import com.google.api.client.auth.oauth2.draft10.AccessProtectedResource.Method;
import com.google.api.client.auth.oauth2.draft10.AccessTokenErrorResponse;
import com.google.api.client.auth.oauth2.draft10.AccessTokenResponse;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.auth.oauth2.draft10.GoogleAccessTokenRequest.GoogleAuthorizationCodeGrant;
import com.google.api.client.googleapis.auth.oauth2.draft10.GoogleAccessProtectedResource;
import com.google.api.client.googleapis.auth.oauth2.draft10.GoogleAuthorizationRequestUrl;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.Arrays;

@SuppressWarnings({ "deprecation", "unused" })
public class connect{

    public void setUp() throws IOException {

        HttpTransport httpTransport = new NetHttpTransport();
        JacksonFactory jsonFactory = new JacksonFactory();

        // The clientId and clientSecret are copied from the API Access tab on
        // the Google APIs Console
        String clientId = "MYCLIENTID";
        String clientSecret = "CLIENTSECRET";

        // Or your redirect URL for web based applications.
        String redirectUrl = "urn:ietf:wg:oauth:2.0:oob";
        String scope = "https://www.googleapis.com/auth/calendar";

        // Step 1: Autorizzazione -->
        String authorizationUrl = new GoogleAuthorizationRequestUrl(clientId, redirectUrl, scope)
            .build();

        // Point or redirect your user to the authorizationUrl.
        System.out.println("Vai al seguente indirizzo nel browser:");
        System.out.println(authorizationUrl);

        // Read the authorization code from the standard input stream.
        System.out.println("Qual e' il tuo codice di autorizzazione?");
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        String code = in.readLine();

        // Fine Step 1 <--
        // Step 2: Scambio -->
        AccessTokenResponse authResponse = new GoogleAuthorizationCodeGrant(httpTransport, jsonFactory,
                clientId, clientSecret, code, redirectUrl).execute();
        System.out.println("Scrivi: "+authResponse);
        System.out.println("Token d'accesso: "+authResponse.accessToken);
        if(scope == "https://www.googleapis.com/auth/calendar")
        System.out.println("Scope di lettura e scrittura usato :"+scope);
        else
            System.out.println("Scope di sola lettura usato :"+scope);
        // Fine Step 2 <--

        GoogleAccessProtectedResource accessProtectedResource = new GoogleAccessProtectedResource(
                authResponse.accessToken, httpTransport, jsonFactory, clientId, clientSecret,
                authResponse.refreshToken);
        System.out.println("Il Client ID utilizzato e': "+accessProtectedResource.getClientId());
        System.out.println("Il Secret ID utilizzato e': "+accessProtectedResource.getClientSecret());
        System.out.println("L'url di autenticazione e': "+accessProtectedResource.getAuthorizationServerUrl());

        com.google.api.services.calendar.Calendar service = new com.google.api.services.calendar.Calendar(httpTransport, jsonFactory);
        Calendar cale = new Calendar();

        System.out.println("Menu'");
        System.out.println("Cosa desideri fare?");
        System.out.println("1) Creare un calendario");
        System.out.println("2) Creare un evento");
        System.out.println("3) Eliminare un calendario");
        System.out.println("0) Uscita");

        int scelta = Integer.parseInt(in.readLine());
        System.out.println(scelta);
        switch(scelta){
        case 1:
            //insert calendar
            Calendar ClaudioCal = new Calendar();
            ClaudioCal.setSummary("Esempio di calendario di Claudio");
            ClaudioCal.setTimeZone("America/Los_Angeles");

            cale = service.calendars().insert(ClaudioCal).execute();
            break;

            //other case.......

        System.out.println("Fatto"); 
    }
    }

大家好,这是我连接 Google 帐户以修改日历的代码,但每次系统都会回复我“未经授权”。就像 accessToken 没有经过验证一样,我不明白问题出在哪里

请帮帮我 提前非常感谢

【问题讨论】:

  • 请提供有关所发生情况的分步信息。你什么时候得到未经授权的异常?堆栈跟踪是什么? HTTP 响应的正文中是否有信息可以告诉您有关错误原因的更多信息?您是否在 google APIs 控制台中为您的项目启用了日历 API?等
  • 日历api已启用,此时System.out.println(authorizationUrl);我浏览它,然后单击允许访问我的 progett 和代码 appaer。我将它复制到我的程序中 String code = in.readLine();比我在我的菜单中设置创建日历时,此时 cale = service.calendars().insert(ClaudioCal).execute();程序因未经授权的异常而失败...似乎我的程序没有使用 accessToken 验证代码

标签: oauth calendar authorization


【解决方案1】:

在最新版本的 Java API 库中,处理 OAuth 的机制发生了显着变化。

您需要遵循此处示例代码中引用的构建器模式: http://code.google.com/p/google-api-java-client/source/browse/calendar-cmdline-sample/src/main/java/com/google/api/services/samples/calendar/cmdline/CalendarSample.java?repo=samples#57

Credential credential = OAuth2Native.authorize(
    HTTP_TRANSPORT, JSON_FACTORY, new LocalServerReceiver(),
    Arrays.asList(CalendarScopes.CALENDAR));

// set up global Calendar instance
client = com.google.api.services.calendar.Calendar.builder(HTTP_TRANSPORT, JSON_FACTORY)
    .setApplicationName("Google-CalendarSample/1.0").setHttpRequestInitializer(credential)
    .build();

这会自动为您处理提示(甚至可以在桌面上发挥一些神奇的作用来打开浏览器)。或者,如果您正在寻找如何在幕后做到这一点,更多信息在这里: http://code.google.com/p/google-api-java-client/source/browse/shared/shared-sample-cmdline/src/main/java/com/google/api/services/samples/shared/cmdline/oauth2/OAuth2Native.java?repo=samples#102

【讨论】:

  • 当核心转到 Oauth2Native 类中的 loadClientSecret 时,它会正确加载客户端 ID 和客户端密码,但是当他使用变量 clientSecrets 执行 GoogleAuthorizationCodeFlow.Builder() 时,如果我这样设置,它会失败GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(transport, jsonFactory, "clientId", "clientSecret", scopes).build();一切正常。为什么在 clientSecrets 变量失败之前? (clientSecrets 是一个 GoogleClientSecrets 对象) Preconditions.checkArgument 方法也失败了,因为他试图评估文件上的错误条件
【解决方案2】:

设置 GoogleAccessProtectedResource 对象后,您没有将其正确传递到日历服务类。

改变这个:

com.google.api.services.calendar.Calendar service = 
    new com.google.api.services.calendar.Calendar(httpTransport,
                                                  jsonFactory);

到这里:

com.google.api.services.calendar.Calendar service = 
    new com.google.api.services.calendar.Calendar(httpTransport, 
                                                  accessProtectedResource, 
                                                  jsonFactory);

应该可以的。

【讨论】:

  • 构造函数 Calendar(HttpTransport, GoogleAccessProtectedResource, JacksonFactory) 未定义
  • 我有这些 import import com.google.api.services.calendar.Calendar; //import com.google.api.services.calendar.model.Calendar; //import com.google.api.services.calendar.Calendar.Calendars;
  • 因此,看起来 OAuth 的处理方式随着库的最新版本完全改变了。我将在下面以最新库的更新方式再次回答。
  • 但我已经下载了 apis google 库的最新版本,即 1.9.0,但日历的构造函数没有第三个参数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-11-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多