OAuth的谷歌2 API刷新令牌为空 [英] OAuth 2 Google API refresh token is null

查看:1382
本文介绍了OAuth的谷歌2 API刷新令牌为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在开发Asp.NET MVC5应用下面这个谷歌示例$ C $ç

I am developing an Asp.NET MVC5 App following this Google sample code.

我想要的应用程序来进行身份验证和用户创建的accessToken(配置阶段),后来我需要能够使用刷新令牌(无需用户干预调用谷歌的API(目录API在我的情况),类似离线)。

I want the app to be authenticated and create an accesstoken (Configure stage) by a user and later on I need to be able to call Google APis' (Directory API in my case) using a refresh token (without user intervention, something like "offline").

控制器:

public async Task<ActionResult> IndexAsync(CancellationToken cancellationToken)
{
    var result = await new AuthorizationCodeMvcApp(this, new AppFlowMetadata()).
                        AuthorizeAsync(cancellationToken);

        if (result.Credential != null)
        {
          var service = new Google.Apis.Admin.Directory.directory_v1.DirectoryService(new BaseClientService.Initializer
                        {
                            HttpClientInitializer = result.Credential,
                            ApplicationName = "My Application"
                        });
                      return View();
        }
        else
        {
             return new RedirectResult(result.RedirectUri);
        }
}         

FlowMetadata实现。 (我现在用FiledataStore略有修改(GoogleFileDataStore))

FlowMetadata implementation. (I have am using FiledataStore slightly modified (GoogleFileDataStore))

public class AppFlowMetadata : FlowMetadata
    {
        //Move to settings
        static readonly string clientId = "xxxccnvofsdfsfoj.apps.googleusercontent.com";
        static readonly string clientsecret = "xxxxxxxxxxLvtC6Qbqpp4x_";
        static readonly string datastore = "AdminSDK.Api.Auth.Store";


         private static readonly IAuthorizationCodeFlow flow =
            new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
                {
                    ClientSecrets = new ClientSecrets
                    {
                        ClientId = clientId,
                        ClientSecret = clientsecret
                    },
                    Scopes = new[] { DirectoryService.Scope.AdminDirectoryUser, DirectoryService.Scope.AdminDirectoryUserAliasReadonly },
                    DataStore = new GoogleFileDataStore(datastore)
                });


        public override string GetUserId(Controller controller)
        {           
            return ConfigHelper.UserID.ToString();
        }

        public override IAuthorizationCodeFlow Flow
        {
            get { return flow; }
        }
    }

当我调用IndexAsync控制器,因为没有的accessToken该用户的previous,它创建的谷歌帐户的用户登录后,一个新的。结果
这是一个简单的accessToken,

When I invoke the IndexAsync controller, as there is no previous accesstoken for the user, it creates a new one after the user sign in to the Google account.
This is a sample accesstoken,

{<$c$c>\"access_token\":\"ya29.5gBOszGO-oYJJt4YZfF6FeaZth1f69_.....\",\"token_type\":\"Bearer\",\"expires_in\":3600,\"Issued\":\"2014-12-24T16:02:32.014+05:30\"}

问题1:为什么没有Refreshtoken存储与此?我怎样才能检索refreshtoken?
问题2:如果我拿到refreshtoken,我应该怎么修改code创建一个新的访问令牌和调用API(当的accessToken已过期)?
[我提到<一个href=\"http://stackoverflow.com/questions/25144667/using-the-youtube-v3-data-api-for-net-how-is-it-possible-to-get-a-refresh-toke\">this问题,但有丢失刷新令牌没有合适的答案。

Question1: Why there is no Refreshtoken stored with this? How can I retrieve a refreshtoken? Question 2: If I get the refreshtoken, how should I modify the code to create a new access token and call the API (when the accesstoken is expired)? [I referred to this question , but there was no proper answer for missing refresh token.

推荐答案

找到了谷歌API离线访问解决方案,以获得刷新令牌,并使用刷新令牌来创建一个新的accessToken,

Found the solution for Google API offline access to get the refresh token and use refresh token to create a new accesstoken,

问题1:为什么没有Refreshtoken存储与此?我怎样才能检索refreshtoken?

Question1: Why there is no Refreshtoken stored with this? How can I retrieve a refreshtoken?

我必须设置ACCESS_TYPE为脱机(默认情况下它是在线)请求。 这里提到

I have to set the access_type as offline (by default it is online) in the request. as mentioned here

我不得不写我自己的GoogleAuthorization codeFLOW类实现。由于<一个href=\"http://stackoverflow.com/questions/22094599/google-analytics-oauth-with-accesstype-offline-in-c-sharp\">this帖子。

I had to write my own implementation for GoogleAuthorizationCodeFlow class. Thanks to this post.

 public class ForceOfflineGoogleAuthorizationCodeFlow : GoogleAuthorizationCodeFlow
    {
        public ForceOfflineGoogleAuthorizationCodeFlow(GoogleAuthorizationCodeFlow.Initializer initializer) : base(initializer) { }

        public override AuthorizationCodeRequestUrl CreateAuthorizationCodeRequest(string redirectUri)
        {
            return new GoogleAuthorizationCodeRequestUrl(new Uri(AuthorizationServerUrl))
            {
                ClientId = ClientSecrets.ClientId,
                Scope = string.Join(" ", Scopes),
                RedirectUri = redirectUri,
                AccessType = "offline",
                ApprovalPrompt = "force"
            };
        }
    };

问题2:..ow我应该修改code创建一个新的访问令牌和调用API

Question2: ..ow should I modify the code to create a new access token and call the API?

    //try to get results
    var result = await new AuthorizationCodeMvcApp(this, new AppFlowMetadata()).
                    AuthorizeAsync(cancellationToken);


    //// This bit checks if the token is out of date, 
    //// and refreshes the access token using the refresh token.
    if (result.Credential.Token.IsExpired(SystemClock.Default))
    {
           Google.Apis.Auth.OAuth2.Responses.TokenResponse token = new Google.Apis.Auth.OAuth2.Responses.TokenResponse();
           //If the token is expired recreate the token
           token = await result.Credential.Flow.RefreshTokenAsync(ConfigHelper.UserID.ToString(), result.Credential.Token.RefreshToken, CancellationToken.None);

            //Get the authorization details back
            result = await new AuthorizationCodeMvcApp(this, new AppFlowMetadata()).AuthorizeAsync(cancellationToken);
     }

这为我工作!希望这将有助于其他人......

This worked for me! Hope this will help others....

这篇关于OAuth的谷歌2 API刷新令牌为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆