Mihajlo Racic
Mihajlo Racic

Reputation: 13

How do I recive instagram log in token using ajax

I am trying to recive token from Instagram and I am having some problems. I use this code, but I get these errors:

SEC7127: Redirect was blocked for CORS request.

SCRIPT7002: XMLHttpRequest: Network Error 0x2ef1, Could not complete the operation due to error 00002ef1.

$(document).ready(function() {
    var clientId = 'xxx';
    var clientSecret = 'xxx';
    var redirectUri = 'http://localhost/instagramFeed/';
  
  function callback(code) {
        $.ajax({
            type: 'POST',
            client_id: clientId,
            client_secret: clientSecret,
            grant_type: authorization_code,
            redirect_uri: redirectUri,
            code: code,
            success: function(code) {
                console.log('Callbeck success!');
            },
            error: function(msg) {
                console.log('Error in callback');
                console.log(msg);
            }
        });
    }
    var requestToken = function() {
        var url = 'https://instagram.com/oauth/authorize/?client_id=' + clientId + '&redirect_uri=' + redirectUri + '&response_type=code';
        $.ajax({
            type: 'GET',
            url: url,
            success: function(code) {
                console.log('Success' + code);
                callback(code);
            },
            error: function(msg) {
                console.log('Error');
                console.log(msg);
            }
        });
    };
    requestToken();
});

Upvotes: 1

Views: 1893

Answers (1)

krisrak
krisrak

Reputation: 12952

Bunch of things wrong: The code will arrive as url param in the redirect url, you cannot make ajax get call and get the code in response. And you cannot make server explicit oauth login with just javascript, you have to do the post on server side code.

If u want to just do using javascript, then you can use the client implicit grant method of oauth2 that is supported by Instagram, you have to enable this is app settings.

All you have to do is open the auth url with response_type=token instead of =code.

window.location = 'https://instagram.com/oauth/authorize/?client_id=' + clientId + '&redirect_uri=' + redirectUri + '&response_type=token'

just open this url and after login, the access_token will be in the hash fragment of redirect url

to grab it, just have this code in the redirect url page

var access_token = "";
if (window.location.hash){
    access_token = window.location.hash.split("access_token=")[1];
    window.location.hash = "";
}

More details here: https://www.instagram.com/developer/authentication/

Upvotes: 1

Related Questions