4

所以我有这个代码
我的问题是如何配置UserCredential如果我已通过OAuth验证?如果我已经具有访问令牌的值,如何创建UserCredential的实例?

当前的情况是代码将显示另一个登录页面重定向到谷歌。因为我已经通过OAuth使用asp.net MVC进行了身份验证,并且我已经拥有令牌如何摆脱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>(); 

我只是新来的这种东西。

回答

8

假设你已经拥有令牌,你可以做以下

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 Client Libraries > .NET > OAuth 2.0

+0

只是一个跟进的问题@Nkosi如何在UserCredential中设置刷新标记? credential.Token.RefreshToken =“[your_access_token_here]”是否正确?因为我不断收到“访问令牌已过期,但我们无法刷新它”。 –

+0

@PeinceJea。检查更新 – Nkosi

+0

@PeinceJea。您在创建'TokenResponse'时包含刷新标记。 GoogleAuthorizationCodeFlow会根据您的刷新令牌和客户端机密获取新的访问令牌。 – Nkosi

相关问题