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

5.7k Views Asked by At

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!

3

There are 3 best solutions below

3
On BEST ANSWER

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

0
On

use window.location.href to avoid cors issues

window.location.href = https://api.instagram.com/oauth/authorize/?app_id=${clientId}&redirect_uri=${redirectUri}&scope=${scope}&response_type=${responseType}

0
On

you can't unless its hosted in your domain or you own the url.

you can refer to this http://en.wikipedia.org/wiki/Same-origin_policy

if you are the owner of the server you can use htaccess to solve your problem. a question about how to solve that is in stackoverflow also..

Happy coding! :D