How to refresh a Google OAuth2 AccessToken

十年热恋 提交于 2019-12-10 20:33:14

问题


I have seen a lot of questions about this with varying answers. Some are for different languages. It is not clear to me the correct way to handle this issue.

This is what I have come up with:

public bool Init()
{
    UserCredential credential;
    ClientSecrets secrets = new ClientSecrets()
    {
        ClientId = m_ClientID,
        ClientSecret = m_ClientSecret
    };

    if (!m_LogFilePathSet)
        return false;

    try
    {
        credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
            secrets,
            m_Scopes,
            "user",
            CancellationToken.None,
            new FileDataStore("MSAToolsSoftware.GMail.Application")).Result;

        if (credential.Token.IsExpired(Google.Apis.Util.SystemClock.Default))
        {
            var refreshResult = credential.RefreshTokenAsync(CancellationToken.None).Result;
        }

        var initializer = new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = m_ApplicationName
        };
        m_Service = new GmailService(initializer);
    }
    catch(Exception ex)
    {
        SimpleLog.Log(ex);
        return false;
    }

    return true;
}

Is this the correct way to refresh the access token (if required)?

Thank you.

来源:https://stackoverflow.com/questions/56575181/how-to-refresh-a-google-oauth2-accesstoken

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