Search code examples
javascriptajaxinstagramaccess-tokensame-origin-policy

Instagram API access_token request and Access-Control-Allow-Origin


Context

I'm trying to get an access token from the Instagram API using their server-side/explicit flow.

When a user successfully authenticates and authorizes my application, Instagram redirects the user to my redirect_uri with a code parameter. Once I've got this code, I'm trying to call the Instagram API in order to get the access_token.

Problem

I successfully get this code but in order to make this exchange, I have to POST the code, along with some app identification parameters to their access_token endpoint:

$.ajax({
    type: 'POST',
    url: 'https://api.instagram.com/oauth/access_token',
    // Disable credentials as they were enabled by default
    xhrFields: {
        withCredentials: false
    },
    crossDomain: true,
    data: {
        client_id: client_id,
        client_secret: client_secret,
        grant_type: 'authorization_code',
        redirect_uri: callback_http,
        code: token
    },
    }).always(function(res) {
    console.log('Res from Instagram API', res);
    });

The problem is that I get an Access-Control-Allow-Origin issue:

XMLHttpRequest cannot load https://api.instagram.com/oauth/access_token.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin '[here is my callback_http]' is therefore not allowed access.

I've tried using dataType: 'jsonp' as a parameter of the Ajax call without any success (401 code).

Any ideas? Thank you very much in advance for your help!


Solution

  • You have to use server side code for oauth when using serverside explicit flow, it is blocked by browser because of cross-origin request. if you want to use only javascript then use the client side implicit flow