GAE / GWT java应用程序中的OAuth2令牌无效

时间:2012-09-04 14:57:28

标签: java google-app-engine gwt oauth-2.0

我正在开发一个GWT / GAE java应用程序

  1. 只需通过GWT地理位置实现获取用户位置(效果非常好)
  2. 点击按钮上的
  3. 应将纬度,经度和准确度写入Google电子表格
  4. 当我点击“保存到电子表格”按钮时,我在eclipse控制台中收到以下错误消息:

    04.09.2012 16:44:01 com.google.appengine.repackaged.org.apache.http.impl.client.DefaultRequestDirector handleResponse
    WARNUNG: Authentication error: Unable to respond to any of these challenges: {authsub=WWW-Authenticate: AuthSub realm="https://www.google.com/accounts//AuthSubRequest"}
    com.google.gdata.client.GoogleService$SessionExpiredException: OK
    <HTML>
    <HEAD>
    <TITLE>Token invalid - Invalid token: Stateless token parent not found</TITLE>
    </HEAD>
    <BODY BGCOLOR="#FFFFFF" TEXT="#000000">
    <H1>Token invalid - Invalid token: Stateless token parent not found</H1>
    <H2>Error 401</H2>
    </BODY>
    </HTML>
    at com.google.gdata.client.http.GoogleGDataRequest.handleErrorResponse(GoogleGDataRequest.java:570)
    at com.google.gdata.client.http.HttpGDataRequest.checkResponse(HttpGDataRequest.java:560)
    at com.google.gdata.client.http.HttpGDataRequest.execute(HttpGDataRequest.java:538)
    at com.google.gdata.client.http.GoogleGDataRequest.execute(GoogleGDataRequest.java:536)
    at com.google.gdata.client.Service.getFeed(Service.java:1135)
    at com.google.gdata.client.Service.getFeed(Service.java:998)
    at com.google.gdata.client.GoogleService.getFeed(GoogleService.java:645)
    at com.google.gdata.client.Service.getFeed(Service.java:1017)
    at com.cloudpilots.locator.server.GSpreadsheetServiceImpl.insertRow(GSpreadsheetServiceImpl.java:42)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at com.google.appengine.tools.development.agent.runtime.Runtime.invoke(Runtime.java:115)
    at com.google.gwt.user.server.rpc.RPC.invokeAndEncodeResponse(RPC.java:569)
    at com.google.gwt.user.server.rpc.RemoteServiceServlet.processCall(RemoteServiceServlet.java:208)
    at com.google.gwt.user.server.rpc.RemoteServiceServlet.processPost(RemoteServiceServlet.java:248)
    at com.google.gwt.user.server.rpc.AbstractRemoteServiceServlet.doPost(AbstractRemoteServiceServlet.java:62)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:511)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1166)
    at com.google.appengine.tools.development.HeaderVerificationFilter.doFilter(HeaderVerificationFilter.java:35)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
    at com.google.appengine.api.blobstore.dev.ServeBlobFilter.doFilter(ServeBlobFilter.java:60)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
    at com.google.apphosting.utils.servlet.TransactionCleanupFilter.doFilter(TransactionCleanupFilter.java:43)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
    at com.google.appengine.tools.development.StaticFileFilter.doFilter(StaticFileFilter.java:125)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
    at com.google.appengine.tools.development.BackendServersFilter.doFilter(BackendServersFilter.java:97)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
    at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:388)
    at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
    at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:182)
    at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:765)
    at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:418)
    at com.google.appengine.tools.development.DevAppEngineWebAppContext.handle(DevAppEngineWebAppContext.java:94)
    at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
    at com.google.appengine.tools.development.JettyContainerService$ApiProxyHandler.handle(JettyContainerService.java:370)
    at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
    at org.mortbay.jetty.Server.handle(Server.java:326)
    at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:542)
    at org.mortbay.jetty.HttpConnection$RequestHandler.content(HttpConnection.java:938)
    at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:755)
    at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:218)
    at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:404)
    at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:409)
    at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:582)
    

    所以它必须是凭证/令牌的问题。

    以下是服务器端RPC服务代码:

    public class GSpreadsheetServiceImpl extends RemoteServiceServlet implements
            GSpreadsheetService {
    
        @Override
        public void insertRow(String latitude, String longitude, String accuracy) {
    
            try {
                String userId = UserServiceFactory.getUserService().getCurrentUser().getUserId();
                Credential credential = OAuth2Utils.initializeFlow().loadCredential(userId);
    
                SpreadsheetService service = new SpreadsheetService("Locator-v1");
    
                service.setOAuth2Credentials(credential);
    
                // Define the URL to request.  This should never change.
                URL SPREADSHEET_FEED_URL = new URL(
                    "https://spreadsheets.google.com/feeds/spreadsheets/private/full");
    
                // Make a request to the API and get all spreadsheets.
                SpreadsheetFeed feed = service.getFeed(SPREADSHEET_FEED_URL,
                    SpreadsheetFeed.class);
                List<SpreadsheetEntry> spreadsheets = feed.getEntries();
    
                // TODO: Choose a spreadsheet more intelligently based on your
                // app's needs.
                SpreadsheetEntry spreadsheet = spreadsheets.get(0);
                for (SpreadsheetEntry spreadsheetEntry : spreadsheets) {
                    if (spreadsheetEntry.getKey() == "MY_SPREADSHEET_KEY") {
                        spreadsheet = spreadsheetEntry;
                        break;
                    }
                }
    
                // Get the first worksheet of the first spreadsheet.
                // TODO: Choose a worksheet more intelligently based on your
                // app's needs.
                WorksheetFeed worksheetFeed = service.getFeed(
                    spreadsheet.getWorksheetFeedUrl(), WorksheetFeed.class);
                List<WorksheetEntry> worksheets = worksheetFeed.getEntries();
                WorksheetEntry worksheet = worksheets.get(0);
    
                // Fetch the list feed of the worksheet.
                URL listFeedUrl = worksheet.getListFeedUrl();
                ListFeed listFeed = service.getFeed(listFeedUrl, ListFeed.class);
    
                // Create a local representation of the new row.
                ListEntry row = new ListEntry();
                row.getCustomElements().setValueLocal("Latitude", latitude);
                row.getCustomElements().setValueLocal("Longitude", longitude);
                row.getCustomElements().setValueLocal("Accuracy", accuracy);
    
                // Send the new row to the API for insertion.
                row = service.insert(listFeedUrl, row);
            } catch (ServiceException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    
        }
    
    }
    

    以下是OAuth2Utils类:

    public class OAuth2Utils {
        /** Global instance of the HTTP transport. */
        static final HttpTransport HTTP_TRANSPORT = new UrlFetchTransport();
    
        /** Global instance of the JSON factory. */
        static final JsonFactory JSON_FACTORY = new JacksonFactory();
    
        static String getRedirectUri(HttpServletRequest req) {
            GenericUrl url = new GenericUrl(req.getRequestURL().toString());
            url.setRawPath("/oauth2callback");
            return url.build();
        }
    
        static GoogleAuthorizationCodeFlow initializeFlow() throws IOException {
            return new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT,
                    JSON_FACTORY, "MY_CLIENT_ID",
                    "MY_KEY",
                    Collections.singleton("https://spreadsheets.google.com/feeds/"))
                    .setCredentialStore(new AppEngineCredentialStore())
                    .setAccessType("offline").build();
        }
    }
    

    有人知道问题是什么吗?

    致以最诚挚的问候,

    Juri Wiens

1 个答案:

答案 0 :(得分:1)

这种方式有效:

1)对OAuth使用Google驱动器DrEdit示例https://developers.google.com/drive/examples/java

注意:你需要添加刷新令牌,我发现添加它并不难。

2)像这样连接:

    SpreadsheetService service = new SpreadsheetService("cellmaster-v0.2");

    // Authorize the service object for a specific user (see other sections)
    service.setHeader("Authorization", "Bearer " + accessToken);


    URL SPREADSHEET_FEED_URL = getSpreadsheetUrl(spreadsheetKey);
    spreadsheet = service.getEntry 
            (SPREADSHEET_FEED_URL, SpreadsheetEntry.class);

我看了很多例子。我花了几天时间才找到这个解决方案。