OAuth 2 Google API refresh token is null

谁都会走 提交于 2019-12-03 20:17:12
Dhanuka777

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

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

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

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"
            };
        }
    };

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....

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!