使用Google API从刷新令牌获取访问令牌

时间:2013-06-18 05:43:28

标签: c#-4.0 oauth-2.0 google-plus access-token

我在我的应用程序中使用了google + api for .NET。使用this中提供的示例 网站我能够获得访问令牌。

我的问题是如何使用OAuth 2.0从刷新令牌中获取访问令牌。我没有找到任何从刷新令牌获取访问令牌的示例。

我已经引用了[google + API参考],但是他们已经使用HTTP方法提到了它。2请使用google + API提供的方法在C#中提供一些示例。

1 个答案:

答案 0 :(得分:1)

首次,您需要从浏览器提示中获取访问令牌,然后将其保存在某个商店中。

检查令牌是否已过期,然后尝试刷新它。

代码在这里:

private static IAuthorizationState GetAuthentication(NativeApplicationClient arg)
    {
        try
        {

            // Get the auth URL:
            var config = new Configuration();
            var calendarScope = Google.Apis.Util.Utilities.ConvertToString(CalendarService.Scopes.Calendar);
            IAuthorizationState state = new AuthorizationState(new[] { calendarScope });
            state.Callback = new Uri(NativeApplicationClient.OutOfBandCallbackUrl);
            Uri authUri = arg.RequestUserAuthorization(state);
            var authCode = String.Empty;

            if (String.IsNullOrWhiteSpace(config.AccessToken) || config.AccessTokenExpirationTime < DateTime.Now || String.IsNullOrWhiteSpace(config.RefreshToken))
            {

                // Request authorization from the user (by opening a browser window):
                Process.Start(authUri.ToString());
                do
                {
                  authCode = Prompt.ShowDialog("Test", "123");
                } while (String.IsNullOrWhiteSpace(authCode));
                state = arg.ProcessUserAuthorization(authCode, state);
            }
            else
            {
                state.AccessToken = config.AccessToken;
                state.AccessTokenExpirationUtc = config.AccessTokenExpirationTime;
                state.AccessTokenIssueDateUtc = config.AccessTokenIssueTime;
                state.RefreshToken =config.RefreshToken ;
                if (state.AccessTokenExpirationUtc < DateTime.Now)
                {
                    var tokenRefreshed = arg.RefreshToken(state);
                    if (tokenRefreshed)
                    {
                        config.AccessToken = state.AccessToken;
                        config.AccessTokenExpirationTime = state.AccessTokenExpirationUtc;
                        config.AccessTokenIssueTime = state.AccessTokenIssueDateUtc;
                        config.RefreshToken = state.RefreshToken;
                        arg.ProcessUserAuthorization(authCode, state);
                    }
                    else
                    {
                        throw new ApplicationException("Unable to refresh the token.");
                    }
                }
            }
            return state;
        }
        catch (System.Exception exp)
        {
            throw new ApplicationException("Failed to get authorisation from Google Calender.", exp);
        }
    }