javascriptnode.jsoauthopenidbattlenet-api

Authorization via battle.net


I try to create auth on my site via battle.net. It's my first experience in OAuth. There is documentation https://develop.battle.net/documentation/api-reference/oauth-api

Now I can get code and want to get access token by code. I provide credentials. Using Koa.js.

const { code } = ctx.query;
  const redirect_uri = 'http://127.0.0.1:3000/auth';
  const client_id = '0010d...25f44b31...5c34b12f4af7'
  const secret = 'MY_VERY_SECRET_CODE';
  const scope = 'wow.profile';
  if( !code ) ctx.redirect(`https://us.battle.net/oauth/authorize?response_type=code&client_id=${client_id}&redirect_uri=${redirect_uri}&scope=${scope}`);

  try {
    const { data } = await axios.post('https://us.battle.net/oauth/token', {
      grant_type: 'authorization_code',
      code,
      redirect_uri,
      client_id
    }, {
      auth: {
        username: client_id,
        password: secret
      }
    })
    console.log(data);
  } catch (e) {
    console.error(e)
  }


  ctx.body = {
    message: 'OK',
  }

Redirect works and I got code. But how I should build a query with the gotten code? But I got error

 data:
      { error: 'invalid_request',
        error_description: 'Missing grant type' } },

Solution

  • I should use form data type.

    formData.append('grant_type', 'authorization_code');
          formData.append('code', code);
          formData.append('redirect_uri', redirect_uri);
          formData.append('client_id', client_id);
    
          const { data: authData } = await axios.post('https://eu.battle.net/oauth/token', 
            formData,
            {
              auth: {
                username: client_id,
                password: secret,
              },
              headers: {
                'Content-Type': `multipart/form-data; boundary=${formData._boundary}`,
              }  
            },
          )