Javi
Javi

Reputation: 939

google oauth2 get token javascript post request

I saw some questions and answers about this but couldn't understand what to do. I get this error: XMLHttpRequest cannot load https://accounts.google.com/o/oauth2/token. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:63342' is therefore not allowed access. The response had HTTP status code 400. As I saw from previous posts, this is because I can't make an HTTP POST request to another server. I saw some things about using jsonp but couldn't understand how.. This is the function I use to send the request:

var url = 'https://accounts.google.com/o/oauth2/token';
var payload = {
    grant_type: 'authorization_code',
    code: authResult['code'],
    client_id: clientID,
    client_secret: clientSecret,
    redirect_uri: '',
    dataType: 'jsonp'
};

$.post(url, {
    form: payload
}, function(error, response, body) {
    console.log(body);
});

Upvotes: 2

Views: 3308

Answers (1)

Thom-x
Thom-x

Reputation: 866

Have you registered your app ?

Obtaining OAuth Keys :

  • Visit Google Cloud Console
  • Click CREATE PROJECT button
  • Enter Project Name, then click CREATE
  • Then select APIs & auth from the sidebar and click on Credentials tab

Note: Make sure you have turned on the APIs you need.

The important part is : Authorized Javascript origins: http://localhost:63342, you need to autorize your website domain to access the API.

The endpoint is bad use https://www.googleapis.com/oauth2/v3/token Google Doc:

$.ajax({
    url: "https://www.googleapis.com/oauth2/v3/token",
    data: {
        code :"",
        client_id : "",
        client_secret : "",
        redirect_uri : "",
        grant_type : "authorization_code"
    },
    method: "POST",
    success: function(e){console.log(e)}
});

Upvotes: 1

Related Questions