docs icon indicating copy to clipboard operation
docs copied to clipboard

Device Authorization Flow Node.js Sample Wrong Encoding in Documentation

Open milesstoetzner opened this issue 4 years ago • 1 comments

Description

Device Authorization Flow Node.js sample code is not encoding data correctly.

The sample code passes a JSON object to axios which expects a string. The solution is to correctly encode the parameters.

This problem should apply to all Node.js examples on the documentation page. I tested this only at the device authorization endpoint and token endpoint.

Here is one sample code of the documentation:

var axios = require("axios").default;

var options = {
  method: 'POST',
  url: 'https://YOUR_DOMAIN/oauth/device/code',
  headers: {'content-type': 'application/x-www-form-urlencoded'},
  data: {client_id: 'YOUR_CLIENT_ID', scope: 'SCOPE', audience: 'AUDIENCE'}
};

axios.request(options).then(function (response) {
  console.log(response.data);
}).catch(function (error) {
  console.error(error);
});

The request sent to the device authorization endpoint using the sample code looks as follows. Note, the data is a stringified JSON and not correctly encoded.

 {
    url: 'https://YOUR_DOMAIN/oauth/device/code',
    method: 'post',
    data: '{"client_id":"YOUR_CLIENT_ID","audience":"MASKED"}',
    headers: {
      Accept: 'application/json, text/plain, */*',
      'Content-Type': 'application/x-www-form-urlencoded',
      'User-Agent': 'axios/0.21.1',
      'Content-Length': 78
    },

The error repsonse form the device authorization endpoint

    data: {
      error: 'unauthorized_client',
      error_description: 'Unauthorized or unknown client'
    }

Here is an example from the axios documentation to correctly encode the body:

import qs from 'qs';
const data = { 'bar': 123 };
const options = {
  method: 'POST',
  headers: { 'content-type': 'application/x-www-form-urlencoded' },
  data: qs.stringify(data),
  url,
};
axios(options);

Reproduction

Create a Native Application and follow the tutorial for Device Authorization Flow.

Environment

  • "axios": "^0.21.1",
  • Windows 10

milesstoetzner avatar Jan 19 '21 20:01 milesstoetzner

I think the documentation should either use or at least mention the openid-client library which implements the device flow.

See https://github.com/panva/node-openid-client#device-authorization-grant-device-flow

milesstoetzner avatar Jan 19 '21 22:01 milesstoetzner