5

我正在结合一些 Google API 使用 OAuth 2.0。虽然授权过程很简单,但在初始授权完成后,我遇到了自动授权的问题。

所以:

1. Authorization is done for the first time. (user grants access, I get the token etc etc)
2. User exits the application
3. User starts the application again
4. How to logon automatically here?

在第 4 点,我确实有一个 refresh_token,所以我应该只使用该 request_token 请求一个新令牌。但是我的电话仍然不断收到 401 Unauthorized 结果。

所以我尝试做的是我的应用程序可以静默登录,这样用户就不必每次都授予访问权限。

4

2 回答 2

2

You should be able to refresh OAuth 2.0 token using the following request:

POST /o/oauth2/token HTTP/1.1
Host: accounts.google.com
Content-Type: application/x-www-form-urlencoded

client_id=21302922996.apps.googleusercontent.com&
client_secret=XTHhXh1SlUNgvyWGwDk1EjXB&
refresh_token=1/6BMfW9j53gdGImsixUH6kU5RsR4zwI9lUVX-tqf8JXQ&
grant_type=refresh_token

As pointed in Google OAuth 2.0 documentation.

I just tried it out using curl and it works as expected:

curl -d client_id=$CLIENT_ID -d client_secret=$CLIENT_SECRET -d refresh_token=$REFRESH_TOKEN -d grant_type=refresh_token https://accounts.google.com/o/oauth2/token

{"access_token":"$ACCESS_TOKEN","token_type":"Bearer","expires_in":3600}
于 2011-06-29T16:29:57.720 回答
1

我使用 Google.GData.Client 在 .NET 中执行此操作。一旦我完成了授权过程并保存了令牌,下次我的用户访问该站点时,我会通过生成一个 GOAuthRequestFactory 对象来获取授权。

public GOAuthRequestFactory GetGoogleOAuthFactory(int id)
    {
        // build the base parameters
        OAuthParameters parameters = new OAuthParameters
        {
            ConsumerKey = kConsumerKey,
            ConsumerSecret = kConsumerSecret
        };

        // check to see if we have saved tokens and set
        var tokens = (from a in context.GO_GoogleAuthorizeTokens where a.id = id select a);
        if (tokens.Count() > 0)
        {
            GO_GoogleAuthorizeToken token = tokens.First();
            parameters.Token = token.Token;
            parameters.TokenSecret = token.TokenSecret;
        }

        // now build the factory
        return new GOAuthRequestFactory("somevalue", kApplicationName, parameters);
    }

拥有请求工厂后,我可以调用我有权使用的各种 api 之一并执行以下操作:

// authenticate to the google calendar
CalendarService service = new CalendarService(kApplicationName);
service.RequestFactory = GetGoogleOAuthFactory([user id]);

// add from google doc record
EventEntry entry = new EventEntry();
entry.Title.Text = goEvent.Title;
entry.Content.Content = GoogleCalendarEventDescription(goEvent);

When eventTime = new When(goEvent.StartTime, goEvent.EndTime.HasValue ? goEvent.EndTime.Value : DateTime.MinValue, goEvent.AllDay);
entry.Times.Add(eventTime);

// add the location
Where eventLocation = new Where();
eventLocation.ValueString = String.Format("{0}, {1}, {2} {3}", goEvent.Address, goEvent.City, goEvent.State, goEvent.Zip);
entry.Locations.Add(eventLocation);

Uri postUri = new Uri(kCalendarURL);

// set the request and receive the response
EventEntry insertedEntry = service.Insert(postUri, entry);
于 2011-10-21T20:20:56.093 回答