如果我已经有访问令牌的值,如何创建用户凭据的实例



所以我有这个代码
我的问题是,如果我已经通过OAuth进行身份验证,如何配置用户凭据

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

我只是对这种东西很陌生。

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

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

我们可以直接从访问令牌创建GoogleCredential,并使用它而不是UserCredential。我只是认为这可能对某人有所帮助。以下是GmailService初始化的代码片段:

GoogleCredential cred = GoogleCredential.FromAccessToken(accessToken);
GmailService service = new GmailService(new BaseClientService.Initializer {HttpClientInitializer = cred});

相关内容

  • 没有找到相关文章

最新更新