English 中文(简体)
Oauth 2. 0 谷歌日历认证
原标题:authentication Oauth 2.0 Google Calendar

我尝试使用 Google 账户验证时遇到一个问题, 无法在 Google 上插入/ 从日历中获取事件

i 使用此代码 :

import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.jackson.JacksonFactory;
import com.google.api.services.calendar.Calendar;
import com.google.api.services.calendar.Calendar.Calendars;
import com.google.api.services.calendar.Calendar.Calendars.Insert;
import com.google.api.client.auth.oauth2.draft10.AccessProtectedResource.Method;
import com.google.api.client.auth.oauth2.draft10.AccessTokenResponse;
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.IOException;
import java.io.InputStreamReader;


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

        //connessione Google for unauthorized user for a limited usage
                /*JsonHttpRequestInitializer initializer = new GoogleKeyInitializer("AIzaSyCuWqLpR9G4QhfJ1QMbqh3pa0vul6sd8yQ");
                Plus plus = Plus.builder(new NetHttpTransport(), new JacksonFactory(), new GenericUrl())
                    .setApplicationName("Progetto SITI")
                    .setJsonHttpRequestInitializer(initializer)
                    .build();*/
    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 = " MYSECRETID ";

        // Or your redirect URL for web based applications.
        String redirectUrl = "https://www.googleapis.com/calendar/v3/calendars/{calendarID}";
        String scope = "https://www.googleapis.com/auth/calendar";

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

        // Point or redirect your user to the authorizationUrl.
        System.out.println("Navigate the link on your browser:");
        System.out.println(authorizationUrl);

        // Read the authorization code from the standard input stream.
        System.out.println("What s your authorization code?");
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        String code = in.readLine();
        // EndStep 1 <--

        // Step 2: Change-->
        AccessTokenResponse authResponse = new GoogleAuthorizationCodeGrant(httpTransport, jsonFactory,
                clientId, clientSecret, code, redirectUrl).execute();
        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);
        // End Step 2 <--

        GoogleAccessProtectedResource accessProtectedResource = new GoogleAccessProtectedResource(
                authResponse.accessToken, httpTransport, jsonFactory, clientId, clientSecret,
                authResponse.refreshToken);
        System.out.println("Client ID: "+accessProtectedResource.getClientId());
        System.out.println("Secret ID: "+accessProtectedResource.getClientSecret());
        System.out.println("Authentication Url: "+accessProtectedResource.getAuthorizationServerUrl());

        Calendar prova = new Calendar(httpTransport, jsonFactory);
        Calendar cale = new Calendar(httpTransport, jsonFactory);
        com.google.api.services.calendar.model.Calendar cal = new com.google.api.services.calendar.model.Calendar();
        cal.setSummary("My test Calendar");
        cal.setDescription("This calendar was created with the API v3.");
        cal.setTimeZone("Europe/Amsterdam");
        cal.setLocation("Amsterdam");
        cal.setId("4");
        String summary = cal.getSummary();
        System.out.println(summary);
        prova.calendars().insert(cal);
        prova.calendars().delete("Caldario prova");
        //Calendar calendarService = null;
        //Calendars calendarList = cale.calendars();
        //Insert insert = calendarList.insert(cal);
        //cal = insert.execute();
        System.out.println("Job Done");
      }
}

我不知道为什么每次我运行这个代码 我的浏览器都向我报告这个回应:

{
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "required",
    "message": "Login Required",
    "locationType": "header",
    "location": "Authorization"
   }
  ],
  "code": 401,
  "message": "Login Required"
 }
}

i 复制到浏览器的链接时 i 接受我的工程授权, 但在错误应用后

someone can help me? thanks a lot in advance

问题回答

如果您试图将此用作命令行样本, 您需要更改 :

String redirectUrl =  "https://www.googleapis.com/calendar/v3/calendars/{calendarID}";

String redirectUrl = "urn:ietf:wg:oauth:2.0:oob";

This indicates that you re using OAuth 2.0 for Installed Applications (out of band). Google will give you the authorization code in your browser which you can copy/paste in至 your app.





相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签