简体   繁体   中英

Secure API AuthSub in Java (Google Calendar API)

I would like to authenticate my Google AuthSub requests. Basically I need to generate a private key and respective certificate, upload this certificate to Google, and sign with the key on subsequent calls to Google AuthSub. I think the most straightforward approach is to use Java's keytool as follows:

# Generate the RSA keys and certificate
keytool -genkey -v -alias Example -keystore ./Example.jks\
  -keyalg RSA -sigalg SHA1withRSA\
  -dname "CN=www.example.com, OU=Engineering, O=My_Company, L=Mountain  View, ST=CA, C=US"\
  -storepass changeme -keypass changeme

# Output the public certificate to a file
keytool -export -rfc -keystore ./Example.jks -storepass changeme \
  -alias Example -file mycert.pem

(As specified by http://code.google.com/apis/gdata/docs/auth/authsub.html#keytool )

I uploaded the given certificate, mycert.pem to Google. In my Java client, I then loaded the private key as follows:

PrivateKey key = AuthSubUtil.getPrivateKeyFromKeystore(
                               "Example.jks", "changeme", "Example", "changeme");

No exceptions are thrown upon loading this key. The key is then used during AuthSub calls, as follows.

String requestUrl =
  AuthSubUtil.getRequestUrl("http://www.example.com/RetrieveToken",
                            "https://www.google.com/calendar/feeds/",
                            true,
                            true);
...
// Servlet context, user follows the 'next link' with token attached.
String onetimeUseToken = AuthSubUtil.getTokenFromReply(
                                           httpServletRequest.getQueryString());

// Exchange for the AuthSub token.
String sessionToken = AuthSubUtil.exchangeForSessionToken(onetimeUseToken, key);

// Use the token.
CalendarService.setAuthSubToken(sessionToken, key);

// Get calendars from the user.
URL feedUrl = 
    new URL("https://www.google.com/calendar/feeds/default/owncalendars/full");

// Exception is thrown HERE.
CalendarFeed resultFeed = service.getFeed(feedUrl, CalendarFeed.class);

The exception is not thrown while setting or exchanging the token, but rather upon attempting to access the user's resources. I'm not quite sure what to make of this. The exception is as follows:

Token invalid - Invalid AuthSub token.

I toyed around a bit with https:// versus http:// for the feed URL and scope URL, but with little success, it's possible I haven't tried a certain combination though.

Seems like all of the above works correctly, I just had an irrelevant coding error. For the record, http and https both work as long as one is used consistently (otherwise you get a 'scope' error).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM