从用户获取oath2.0访问令牌和刷新令牌后,如何使用它们在C#和Java中创建PlusService的实例?
目前,我正在使用BaseClientService.Initializer,但这仅适用于匿名应用程序令牌。
我想使用从OAUTH2流程获得的OAuth2Parameters对象创建plus服务的实例。

最佳答案

OAuth2Parameters保存OATH2过程中最后一步的令牌

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


使用您自己的身份验证器实现

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/

10-09 19:51