简体   繁体   中英

x-www-form-urlencoded format - using https in node.js

I am currently writing to an API to try and get a token. I'm nearly there but fallen at the last hurdle..

const fs = require('fs');
const https = require('https');
const ConfigParams = JSON.parse(fs.readFileSync('Config.json', 'utf8'));
const jwt = require('jsonwebtoken');
const apikey = ConfigParams.client_id;


var privateKey = fs.readFileSync(**MY KEY**);
var tkn;

const jwtOptions = {
    algorithm: 'RS512',
    header: { kid: 'test-1' }
}


const jwtPayload = {
    iss: apikey,
    sub: apikey,
    aud: **API TOKEN ENDPOINT**,
    jti: '1',
    exp: 300
}

jwt.sign(jwtPayload,
    privateKey,
    jwtOptions,
    (err, token) => {
        console.log(err);
        //console.log(token);
        tkn = token;

        let = tokenPayload = {
            grant_type: 'client_credentials',
            client_assertion_type: 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer/',
            client_assertion: tkn
        }

        tokenAuthOptions = {
            payload: tokenPayload,
            host: **HOST**,
            path: **PATH**,
            method: 'POST',
            

        }
          
        https.request(
            tokenAuthOptions,
            resp => {
                var body = '';
                resp.on('data', function (chunk) {
                    body += chunk;
                });
                resp.on('end', function () {
                    console.log(body);
                    console.log(resp.statusCode);
                });
            }
        ).end(); 
    }
)

the encoded token comes back fine for the first part, the https request though returns a problem.

the response I get back is grant_type is missing, so I know I have a formatting problem due to this x-www-form-urlencoded, but I can't figure out how to fix it.

here is what the website said:

You need to include the following data in the request body in x-www-form-urlencoded format:

grant_type = client_credentials client_assertion_type = urn:ietf:params:oauth:client-assertion-type:jwt-bearer client_assertion = <your signed JWT from step 4> Here's a complete example, as a CURL command:

curl -X POST -H "content-type:application/x-www-form-urlencoded" --data \\ "grant_type=client_credentials\\ &client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer
&client_assertion="
END POINT

Ideally I want a solution using the https request, but if that's not possible I'm open to other solutions.

Any help is greatly appreciated.

Thanks, Craig

Edit - I updated my code based on a suggestion to:

const params = new url.URLSearchParams({
    grant_type: 'client_credentials',
    client_assertion_type: 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer/',
    client_assertion: tkn
});

axios.post("URL", params.toString()).then(resp => {
    console.log("response was : " + resp.status);
}).catch(err => {
    console.log("there was an error: " + err);
})

But I'm still getting an error code 400, but now with less detail as to why. (error code 400 has multiple message failures)

Postman is the best.

Thank for @Anatoly for your support which helped to point me in the right direction. I had no luck so used postman for the first time, and found it had a code snippet section, with four different ways of achieving this using node.js.

The solution with Axion was:

const axios = require('axios').default;
const qs = require('qs');

        var data = qs.stringify({
            'grant_type': 'client_credentials',
            'client_assertion_type': 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer',
            'client_assertion': tkn
        });
        var config = {
            method: 'post',
            url: '',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            data: data
        };

        axios(config)
            .then(function (response) {
                console.log(JSON.stringify(response.status));
            })
            .catch(function (error) {
                console.log(error);
            });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM