API call for Openshift (e.g. 4.14) to get token using Postman

110 Views Asked by At

I am trying to get via API call token for using it in Openshift so I can be authenticated/authorized and execute more API calls

a) As URL I used "https://oauth-openshift.apps.domain/oauth/authorize?response_type=code&client_id=openshift-browser-client

b) I used basic authentication user/password

c) the only header I used is X-CSRF-Token: xxx

I get response 200, but the token is not shown. It just says "Display Token", but cannot see it

I tried to change the response_type=token, client_id=openshift-challenging-client, but it doesn't work.

How can I get the token in postman to save it and use it in the next API calls (e.g. get pods, projects etc)?

When I use curl (response_type=token, client_id=openshift-challenging-client) from my jump server I get the token, but my target is to do that in postman

curl example that worked curl -v --insecure --user user:password --header "X-CSRF-Token: xxx" --url "https://oauth-openshift.apps.domain/oauth/authorize?response_type=token&client_id=openshift-challenging-client" 2>&1 | grep -oP "access_token=\K[^&]*"

From Postman:

enter image description here

Using resonse=token, client_id=openshift-challenging-client, the return is this. I get 200 with the below message, but test fails enter image description here enter image description here

The "display token" comes when I use response=code, client_id=openshift-browser-client. No error with the test, but I don't get the token again

enter image description here

1

There are 1 best solutions below

0
Bench Vue On

Handling access token in Postman

Postman sets the value of the access_token variable in the Postman environment to the value stored in the Access Token variable.

postman.setEnvironmentVariable("access_token", accessToken);

enter image description here

This sets the access_token as a Bearer Token, allowing it to be accessed using the placeholder {{access_token}}. This token can then be dynamically used in subsequent requests for authentication purposes.

enter image description here

Parsing Access Token in Postman

Input : HTML

<form>
    <input type="hidden" name="csrf" value="abc123token">
    <button type="submit">
      ee7fdbd598bf649359115e05b9a4e476a85ec6d9bc3c99af39476e66bb1db25c
      </button>
</form>

Parsing

var accessToken = htmlResponse.match(/<button type="submit">([^<]+)<\/button>/)[1].trim();

Setting/Getting via 'EnvironmentVariable'

postman.setEnvironmentVariable("access_token", accessToken);
console.log(postman.getEnvironmentVariable("access_token"));

log will display bottom/left side in Postmam enter image description here

Mocking your Openshift server

Save as server.js

const express = require('express');
const cors = require('cors');
const crypto = require('crypto');

let accessToken; // Variable to store the access token

const app = express();

app.use(cors()); // Enable CORS

// Get Token Endpoint
app.get('/oauth/authorize', (req, res) => {

    // Check if Authorization header is present
    if (!req.headers.authorization || req.headers.authorization.indexOf('Basic ') === -1) {
        res.status(401).send('<h1>Unauthorized</h1>');
        return;
    }

    // Extract the base64 encoded credentials
    const base64Credentials = req.headers.authorization.split(' ')[1];

    // Decode the base64 encoded credentials
    const credentials = Buffer.from(base64Credentials, 'base64').toString('ascii');

    // Extract username and password from credentials
    const [username, password] = credentials.split(':');

    // Check if username and password are valid
    if (username !== 'abcd' || password !== '1234') {
        res.status(401).send('<h1>Unauthorized</h1>');
        return;
    }

    const responseType = req.query.response_type;
    const csrfToken = req.headers['x-csrf-token'];
    const clientId = extractClientId(csrfToken);

    // Hash the CSRF token
    accessToken = hashToken(csrfToken);

    // Construct HTML response
    const htmlResponse = `
    <form>
      <input type="hidden" name="csrf" value="${csrfToken}">
      <button type="submit">
      ${accessToken}
      </button>
    </form>
  `;

    res.send(htmlResponse);
});

// Update data API End point 
app.put('/data', (req, res) => {
    const bearerToken = req.headers.authorization;

    // Check if Authorization header is present and contains Bearer token
    if (!bearerToken || bearerToken.indexOf('Bearer ') === -1) {
        res.status(401).json({ error: 'Unauthorized: Bearer token missing' });
        return;
    }

    const accessTokenFromHeader = bearerToken.split('Bearer ')[1]; // Extract the Bearer token

    // Check if the access token matches the expected value
    if (accessTokenFromHeader !== accessToken) {
        res.status(403).json({ error: 'Forbidden: Invalid access token' });
        return;
    }

    const updatedData = { message: "Data updated successfully" };
    res.json(updatedData); // Send the updated data in JSON format
});

// Function to extract client ID from CSRF token
function extractClientId(csrfToken) {
    // For simplicity, let's assume the CSRF token contains the client ID at the end of the token.
    return csrfToken.slice(-20); // Extract last 20 characters as client ID
}

function hashToken(token) {
    return crypto.createHash('sha256').update(token).digest('hex');
}

// Start the server
const port = 3000;
app.listen(port, () => {
    console.log(`Server is running on port ${port}`);
});

Install server dependencies

npm install express cors crypto

Run it

node server.js

enter image description here

cURL testing

User ID : user User Password: 1234

curl \
--silent \
--insecure \
--user abcd:1234 \
--header "X-CSRF-Token: abc123token" \
--url "http://localhost:3000/oauth/authorize?response_type=token&client_id=openshift-challenging-client"

The output will response HTML format as similar your response

enter image description here

Testing by Postman

#1 Get Token

GET http://localhost:3000/oauth/authorize?response_type=token&client_id=openshift-challenging-client

enter image description here

Basic Auth enter image description here

Header enter image description here

Tests

var htmlResponse = pm.response.text();
var accessToken = htmlResponse.match(/<button type="submit">([^<]+)<\/button>/)[1].trim();

postman.setEnvironmentVariable("access_token", accessToken);
console.log(postman.getEnvironmentVariable("access_token"));

enter image description here

Result enter image description here

#2 Update Data call with access token

PUT http://localhost:3000/data

Select Type with Bearer Token and Enter {{access_token}}

enter image description here

It will use some names of Environment variables (my demo is 'dev') In Postman UI, right/top side.

enter image description here

Result of PUT call using access token

Pre-request Script just logging enter image description here

enter image description here


Update

Replace in Tests tab

var htmlResponse = pm.response.text();

var matchResult = htmlResponse.match(/<button type="submit">\s*([^<\s]+)\s*<\/button>/);

// Check if the match result is not null
if (matchResult && matchResult.length > 1) {
    var accessToken = matchResult[1].trim();
    // Set the access token value as a global variable
    postman.setEnvironmentVariable("access_token", accessToken);
} else {
    console.log("Access token not found in the HTML response");
}

console.log(postman.getEnvironmentVariable("access_token"));

If still not finding access token.

You need to find the correct regular expression string

Go this site

https://regex101.com/

Step 1

Put REGULAR EXPRESSION

<button type="submit">\s*([^<\s]+)\s*<\/button>

Put TEST STRING

</style>


<form>
    <input type="hidden" name="code" value="sha256~PcJ_i3E0t84RmewmfRLC5Y0mW29Das2bte5__9sfZ6c">
    <input type="hidden" name="csrf" value="LSt2kbfFXKtyg2M0CHeYTcvlH94_Am0m_wutZc5p6bs">
    <button type="submit">
        ee7fdbd598bf649359115e05b9a4e476a85ec6d9bc3c99af39476e66bb1db25c
    </button>
</form>

Result

enter image description here

Right Side

enter image description here

Both display enter image description here

Step 2

Put REGULAR EXPRESSION As same as Step 1

Put TEST STRING From your Postman's Body Output enter image description here

If matches your token finding, use that regular expression

If still failed, copy your Body and update your question after TOKEN STRING - replace dummy string.