John
John

Reputation: 3

Unable to exchange authorization code for access token in eBay

I'm integrating eBay's OAuth API into my C# application to generate an access_token by exchanging an authorization_code.

However, I get the following error during the token exchange:

{
    "error": "invalid_grant",
    "error_description": "the provided authorization grant code is invalid or was issued to another client"
}

Current implementation

  1. Generating the Authorization URL
    I generate the URL to redirect users to eBay's login page for consent. After the user logs in and grants consent, eBay provides an authorization_code.
    Here's how I generate the URL and prompt users to visit it manually:
string authCodeUrl = BuildAuthorizationUrl();
Console.WriteLine($"Please visit this URL to provide consent: {authCodeUrl}");
System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo
{
    FileName = authCodeUrl,
    UseShellExecute = true
});
  1. Exchanging the Authorization Code for an Access Token
    Once the user manually inputs the authorization_code in the console, I use the following method to exchange it for an access_token:
public async Task<string> GetAccessTokenAsync(string authorizationCode)
{
    string tokenUrl = "https://api.sandbox.ebay.com/identity/v1/oauth2/token";
    string clientId = "<Your Client ID>";
    string clientSecret = "<Your Client Secret>";
    string redirectUri = "http://localhost:8080/"; // Must match the redirect URI in eBay app settings

    using (var client = new HttpClient())
    {
        var authHeader = Convert.ToBase64String(Encoding.ASCII.GetBytes($"{clientId}:{clientSecret}"));
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authHeader);

        var parameters = new Dictionary<string, string>
        {
            { "grant_type", "authorization_code" },
            { "code", authorizationCode },
            { "redirect_uri", redirectUri }
        };

        var content = new FormUrlEncodedContent(parameters);
        var response = await client.PostAsync(tokenUrl, content);

        string responseBody = await response.Content.ReadAsStringAsync();

        if (!response.IsSuccessStatusCode)
        {
            Console.WriteLine($"Error: {responseBody}");
            throw new Exception($"Error retrieving the access token. Response: {responseBody}");
        }

        var tokenResponse = JsonConvert.DeserializeObject<AccessTokenResponse>(responseBody);
        return tokenResponse.access_token;
    }
}

Problem: when I call GetAccessTokenAsync, I consistently get the invalid_grant error.

Expected outcome: a successful response similar to the following:

{
    "access_token": "v^1.1#i^1#p^3#r^1...XzMjRV4xMjg0",
    "expires_in": 7200,
    "refresh_token": "v^1.1#i^1#p^3#r^1...zYjRV4xMjg0",
    "refresh_token_expires_in": 47304000,
    "token_type": "User Access Token"
}

Upvotes: 0

Views: 53

Answers (0)

Related Questions