OAuth 2 Google API refresh token is null

后端 未结 1 1365
无人及你
无人及你 2021-02-11 01:17

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

I want the app to be authenticated and create an accesstoken (Configure stage) by a user and later

相关标签:
1条回答
  • 2021-02-11 01:56

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

    0 讨论(0)
提交回复
热议问题