Question

After obtaining the oath2.0 access token and refresh token from a user, how can these be used to create an instance of the PlusService in C# and java?
Currently I'm using the BaseClientService.Initializer but this only works for the anonymous app tokens. I want to create an instance of the plus service using the OAuth2Parameters object I get from the OAUTH2 process.

Was it helpful?

Solution

OAuth2Parameters hold the tokens of the final step in the OATH2 proccess

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

With your own implementation of the authenticator

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

As of V1.7.0-beta Google.Apis.Authentication.IAuthenticator is deprecated use HttpClientInitializer instead.

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);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top