How to obtain an access token?

Questions and Answers

Moderator: IoTStudio Support

Post Reply
IoTStudio Support
Posts: 39
Joined: Wed Nov 23, 2022 9:26 am

How to obtain an access token?

Post by IoTStudio Support »

Please refer Node-RED link: https://nodered.org/docs/api/admin/oauth

The below is a javascript sample code for reference:

Code: Select all

const http = require('http');
const https = require('https');

function doPost(url, _data, _headers)
{
    var uri = new URL(url);
    
    //
    const { request } = uri.protocol === 'https:' ? https : http;
    
    // Define the data to be sent in x-www-form-urlencoded format
    //const data = 'client_id=node-red-admin&grant_type=password&scope=*&username=admin&password=admin';
    
    // Define the options for the POST request
    const options = {
        hostname: uri.hostname, // Replace with your target URL
        path: uri.pathname, // Replace with the specific endpoint you're targeting
        method: 'POST'
    };
    
    if (uri.port) {
        options.port = uri.port; // Replace with the appropriate port if necessary (e.g., 443 for HTTPS)
    } else {
        options.port = uri.protocol === 'https:' ? 443 : 80;
    }

    options.headers = _headers;
    return new Promise((resolve, reject) =>
    {
        // Create the request object
        const req = request(options, (res) => {
            let responseData = '';
            
            // A chunk of data has been received.
            res.on('data', (chunk) => {
                responseData += chunk;
            });
            
            // The whole response has been received.
            res.on('end', () => {
                resolve(responseData);
            });
        });
        
        // Handle errors
        req.on('error', (e) => {
            reject(`Problem with request: ${e.message}`);
        });
        
        // Write the data to the request body
        req.write(_data);
        
        // End the request
        req.end();
    });
}

function getToken()
{
    var url = new URL("http://127.0.01.1:10200/auth/token");
    const _data = 'client_id=node-red-admin&grant_type=password&scope=*&username=admin&password=admin';
    let _headers = {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Content-Length': Buffer.byteLength(_data)
    };
    
    return new Promise((resolve, reject) => {
        doPost(url, _data, _headers)
            .then((res) => {
                resolve(res);
            })
            .catch((resason) => { reject(resason);});
    });
}

getToken().then((token) => {
	console.log(JSON.parse(token));
});
Best Regards,
IoT Studio Support Team
Post Reply