gpt4 book ai didi

c# - 如何从 token 创建 PlusService 的实例

转载 作者:行者123 更新时间:2023-11-29 05:33:50 25 4
gpt4 key购买 nike

从用户处获取到oath2.0 access token和refresh token后,如何在C#和java中创建PlusService实例?
目前我正在使用 BaseClientService.Initializer 但这仅适用于匿名应用程序 token 。我想使用从 OAUTH2 进程获得的 OAuth2Parameters 对象创建 plus 服务的实例。

最佳答案

OAuth2Parameters 持有 OATH2 过程中最后一步的 token

OAuth2Parameters parameters = new OAuth2Parameters()
{
ClientId = CLIENT_ID,
ClientSecret = CLIENT_SECRET,
AccessCode = token,
RedirectUri = REDIRECT_URI //needed because of a bug
};
OAuthUtil.GetAccessToken(Request.Url.Query, parameters);
BaseClientService.Initializer init = new BaseClientService.Initializer { Authenticator = new AuthenticatorImp(parameters)};
PlusService service = new PlusService(init);
Person me = service.People.Get("me").Execute();

使用您自己的身份 validator 实现

public class AuthenticatorImp : Google.Apis.Authentication.IAuthenticator
{
OAuth2Parameters parameters;
public AuthenticatorImp(OAuth2Parameters parameters)
{
this.parameters = parameters;
}
/// <summary>
/// Takes an existing httpwebrequest and modifies its headers according to
/// the authentication system used.
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public void ApplyAuthenticationToRequest(HttpWebRequest request)
{
if (parameters.TokenType == "Bearer" && parameters.TokenExpiry < DateTime.Now)
{
OAuthUtil.RefreshAccessToken(parameters);
}
request.Headers.Add("Authorization: Bearer " + parameters.AccessToken);
}
}

从 V1.7.0-beta 开始,Google.Apis.Authentication.IAuthenticator 已弃用,改用 HttpClientInitializer。

public class ConfigurableHttpClientInitializer : IConfigurableHttpClientInitializer 
{
OAuth2Parameters parameters;
public ConfigurableHttpClientInitializer(OAuth2Parameters parameters) {
this.parameters = parameters;
}
/// <summary> Initializes an Http client after it was created. </summary>
public void Initialize(ConfigurableHttpClient httpClient)
{
if (parameters.TokenType == "Bearer" && parameters.TokenExpiry < DateTime.Now)
{
OAuthUtil.RefreshAccessToken(parameters);
}
httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + parameters.AccessToken);
}
}

关于c# - 如何从 token 创建 PlusService 的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20187822/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com