简体   繁体   English

使用AccountManager使用Google API进行身份验证

[英]Authenticating with Google API using AccountManager

I've been struggling with this for a couple days now. 我几天都在努力解决这个问题。 I'm trying to make calls to Google Calendar using authentication via Android's AccountManager . 我正试图通过Android的AccountManager使用身份验证拨打Google日历。 I retrieve an auth token using the usual method: 我使用通常的方法检索身份验证令牌:

AccountManager manager = AccountManager.get(this);
String authToken = manager.getAuthToken(account, AUTH_TOKEN_TYPE, true, null, null).getResult().getString(AccountManager.KEY_AUTHTOKEN);

And then, with that token, I create a Calendar instance like this: 然后,使用该令牌,我创建一个这样的Calendar实例:

HttpTransport transport = AndroidHttp.newCompatibleTransport();
JacksonFactory jsonFactory = new JacksonFactory();
GoogleAccessProtectedResource accessProtectedResource = new GoogleAccessProtectedResource(accessToken);
Calendar calendar = Calendar.builder(transport, jsonFactory).setApplicationName("MyApp/1.0").setJsonHttpRequestInitializer(new JsonHttpRequestInitializer() {
    @Override
    public void initialize(JsonHttpRequest request) {
        CalendarRequest calendarRequest = (CalendarRequest) request;
        calendarRequest.setKey(API_KEY);
    }
}).setHttpRequestInitializer(accessProtectedResource).build();

However, when I make API calls using this, I receive the 401 Unauthorized error seen below. 但是,当我使用它进行API调用时,我收到下面看到的401 Unauthorized错误。 Note that I have included code to invalidate expired auth tokens, so I don't believe that's the problem here. 请注意,我已经包含了使过期的auth令牌无效的代码,因此我不认为这是问题所在。

com.google.api.client.googleapis.json.GoogleJsonResponseException: 401 Unauthorized
{
    "code" : 401,
    "errors" : [ {
        "domain" : "global",
        "location" : "Authorization",
        "locationType" : "header",
        "message" : "Invalid Credentials",
        "reason" : "authError"
    } ],
    "message" : "Invalid Credentials"
}

Any thoughts on what I might be doing wrong? 关于我可能做错什么的任何想法?

Yes this is possible. 是的,这是可能的。 Once you have a handle on the Google account (as you described), you just need to request an auth token from the AccountManager for the GData service. 一旦掌握了Google帐户(如您所述),您只需要从AccountManager请求GData服务的身份验证令牌。

If the android device already has an auth token (for the particular GData service you're trying to access), it will be returned to you. 如果Android设备已经有一个身份验证令牌(对于您尝试访问的特定GData服务),它将返回给您。 If not, the AccountManager will request one and return it to you. 如果没有,AccountManager将请求一个并将其返回给您。 Either way, you don't need to worry about this as the AccountManager handles it. 无论哪种方式,您都不需要担心这一点,因为AccountManager会处理它。

In the following example, I am using the Google Spreadsheets API: 在以下示例中,我使用的是Google Spreadsheets API:

ArrayList<Account> googleAccounts = new ArrayList<Account>();

// Get all accounts 
Account[] accounts = accountManager.getAccounts();
  for(Account account : accounts) {
    // Filter out the Google accounts
    if(account.type.compareToIgnoreCase("com.google")) {
      googleAccounts.add(account);
    }
  }
AccountManager accountManager = AccountManager.get(activity);

// Just for the example, I am using the first google account returned.
Account account = googleAccounts.get(0);

// "wise" = Google Spreadheets
AccountManagerFuture<Bundle> amf = accountManager.getAuthToken(account, "wise", null, activity, null, null);

try {
  Bundle authTokenBundle = amf.getResult();
  String authToken = authTokenBundle.getString(AccountManager.KEY_AUTHTOKEN);

  // do something with the token
  InputStream response = sgc.getFeedAsStream(feedUrl, authToken, null, "2.1");

}

AND

Please have a look at the sample code in the google data api. 请查看google data api中的示例代码 The important thing to do after authentication is to call GoogleHeaders.setGoogleLogin(String). 身份验证后要做的重要事情是调用GoogleHeaders.setGoogleLogin(String)。

I hope this helps. 我希望这有帮助。

Ran into a similar issue myself. 我自己也遇到了类似的问题。 I found that I need to set the xoauth_requestor_id in the unknown keys list ( reference : http://www.yenlo.nl/2011/google-calendar-api-v3-and-2lo/ ) 我发现我需要在未知密钥列表中设置xoauth_requestor_id(参考: http ://www.yenlo.nl/2011/google-calendar-api-v3-and-2lo/)

This worked for me: 这对我有用:

com.google.api.services.calendar.Calendar.CalendarList.List list = calendar.calendarList().list();
//Set the requestor id
list.getUnknownKeys().put("xoauth_requestor_id", "user@gmail.com");

After this the API calls went thru. 在此之后,API调用通过了。

I wish there was a explanation as to why the requestor id is needed. 我希望有一个解释为什么需要请求者ID。 Can someone explain? 谁能解释一下?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 是否有使用AccountManager帐户在Android上对Google Data API进行身份验证的官方方法? - Is there an official way to authenticate for Google Data API on Android using AccountManager accounts? 使用Google Calendar API进行身份验证 - Authenticating with Google Calendar API 使用Google验证用户身份 - Authenticating a user using Google 使用Java API向Google云端硬盘进行身份验证时发生异常 - Exception when authenticating to Google Drive using Java API 使用Google的Java API客户端库进行身份验证时出现IllegalArgumentException - IllegalArgumentException when authenticating using Google's Java API client library 在Android上验证Google Cloud API - Authenticating google cloud api on android 使用Java API的服务帐户验证Google API - Authenticating Google API with a service account with Java API 使用 Google API 库进行身份验证,用于 Java 到 Google 云 - Authenticating with Google API library for Java to Google cloud 在Cloud Endpoints和API Explorer上对用户进行身份验证(同时使用Firebase和Google身份验证) - Authenticating users (using both Firebase and Google authentication) on Cloud Endpoints and API Explorer 在服务器端验证Google Drive API,而不提示用户登录 - Authenticating Google Drive API in server side without prompting users to log in
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM