12

所以我有这段代码我的问题是如果我已经通过 OAuth 进行了身份验证,
如何配置UserCredential ?

当前场景是代码将显示另一个登录页面重定向到谷歌。由于我已经使用 asp.net MVC 通过 OAuth 进行了身份验证,并且我已经拥有令牌,如何摆脱GoogleWebAuthorizationBroker并直接传递令牌?

string[] scopes = new string[] {PlusService.Scope.PlusLogin,
                                             PlusService.Scope.UserinfoEmail,
                                             PlusService.Scope.UserinfoProfile};

UserCredential credential = 
GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets
{
    ClientId = "xxx.apps.googleusercontent.com",
    ClientSecret = "xxxx"
},
    scopes,
    Environment.UserName,
    CancellationToken.None,
    new FileDataStore("Store")).Result;

PlusService service = new PlusService(new BaseClientService.Initializer()
{
    HttpClientInitializer = credential,
    ApplicationName = "ArcaneChatV2",
});

PeopleResource.ListRequest listPeople = service.People.List("me", PeopleResource.ListRequest.CollectionEnum.Visible);
listPeople.MaxResults = 10;
PeopleFeed peopleFeed = listPeople.Execute();
var people = new List<Person>();

我对这种东西很陌生。

4

2 回答 2

24

假设您已经拥有令牌,您可以执行以下操作

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); 

然后您可以将您的凭据传递给服务的初始化程序

参考Google API 客户端库 > .NET > OAuth 2.0

于 2016-07-17T20:06:18.960 回答
5

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});
于 2020-03-24T09:58:00.780 回答