Yandri
Yandri

Reputation: 41

oAuth code exchange for secret token

I'm making an app that is supposed to use oAuth to authenticate players from the Blizzard servers, I want to access their character info.. and I can't figure out how to ask for the secret_token. I guess I'm doing my post request wrong below is the code I'm using

app.post('/', function(req, res) {

      var code = req.body.code; //this is the code i get ounce the player is redirected back to my redirect_uri
      var redirectUri = "https://localhost:3000/oauth_callback.html";
      var scope = "wow.profile";

      var key = "they client_id i was given";
      var secret = "they secret I was given";

      var grantType = "authorization_code";
      var tokenUri = "https://us.battle.net/oauth/token";
      var uriBody = "?client_id=" + key + "&client_secret=" + secret + "&grant_type=authorization_code&code=" + code + "&redirect_uri=" + redirectUri + "&scope=" + scope;


  request({
    url: tokenUri, //URL to hit
    method: 'POST',
    headers: { 
        'Content-Type': "application/x-www-form-urlencoded",
    },
    body: uriBody //Set the body as a string
}, function(error, response, body){
    if(error) {
        console.log(error);
    } else {
        console.log(response.statusCode, body);
    }
});

so basically I'm getting the code making a post request to my server with it, and then triggering a post request to the blizzard server trying to exchange my code for an access token.

The error I get is:

401 '{"error":"unauthorized","error_description":"An Authentication object was not found in the SecurityContext"}'

I'm using Node.js & request.js to make the post, my guess is I'm not making a proper request post request?

Upvotes: 0

Views: 365

Answers (2)

Yandri
Yandri

Reputation: 41

finally! here is how I got it to work! qs = query-string.js library...

var token_params = qs.stringify({
      client_id: key,
      client_secret: secret,
      code: code,
      scope: scope,
      grant_type: 'authorization_code',
      redirect_uri: redirectUri
    });

    request('https://us.battle.net/oauth/token?' + token_params, function(error, response, body){
      if (error) {
        console.log(error);
      } else {
        console.log(body) 
      }

    });

Upvotes: 0

abdulbari
abdulbari

Reputation: 6242

I think body key is not acceptable in request.

Send data in json if content-type is JSON or form if content-type is x-www-form-urlencoded

Like this

request({
    url: tokenUri, //URL to hit
    method: 'POST',
    headers: { 
        'Content-Type': "application/x-www-form-urlencoded",
    },
    form: uriBody //Set the body as a string
}, function(error, response, body){
    if(error) {
        console.log(error);
    } else {
        console.log(response.statusCode, body);
    }
}); 

Upvotes: 0

Related Questions