How to create a instance of UserCredential if I already have the value of Access Token?

后端 未结 2 988
温柔的废话
温柔的废话 2020-12-05 20:47

So I have this code
My question is how do I configure the UserCredential if I\'m already authenticated via OAuth?

The current scenario is the c

相关标签:
2条回答
  • 2020-12-05 21:07

    We can create GoogleCredential directly from the access token and use it instead of UserCredential as well. I just think it might be helpful for someone. Here is a code snippet of GmailService initialization:

    GoogleCredential cred = GoogleCredential.FromAccessToken(accessToken);
    GmailService service = new GmailService(new BaseClientService.Initializer {HttpClientInitializer = cred});
    
    0 讨论(0)
  • 2020-12-05 21:25

    Assuming you already have the tokens you can do the following

    string[] scopes = new string[] {
        PlusService.Scope.PlusLogin,
        PlusService.Scope.UserinfoEmail,
        PlusService.Scope.UserinfoProfile
    };
    
    var flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
    {
        ClientSecrets = new ClientSecrets
        {
            ClientId = "xxx.apps.googleusercontent.com",
            ClientSecret = "xxxx"
        },
        Scopes = scopes,
        DataStore = new FileDataStore("Store")
    });
    
    var token = new TokenResponse { 
        AccessToken = "[your_access_token_here]",
        RefreshToken = "[your_refresh_token_here]"
    };
    
    var credential = new UserCredential(flow, Environment.UserName, token); 
    

    Then you can pass your credentials to the service's initializer

    Reference Google API Client Libraries > .NET > OAuth 2.0

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