Where I can find token in postman?

38 views Asked by At

I am struggling with one think in postman (I use it first time). I watched a course where the guy shows where token in postman can be find and we should use it. Unfortunately I can't find in place where it should beenter image description here

I have a free version of this program but it shouldn't be a problem. I am working on active environment

Authorization tab: enter image description here

headers enter image description here

body enter image description here

1

There are 1 answers

0
Bench Vue On

Overview

Postman : Want to get token and update data as client

Server : Provides token and update data

Token API:

GET http://localhost:8000/api/me

Needs username/password

Update Data API:

POST http://localhost:8000/api/data

Needs access token

enter image description here

How works API call from Postman

#1 User Basic Authorization

#2 Get Token API Call

#3 Response Get Token Call

#4 Save access-token into environment variable

#5 Update Data API Call with access token

enter image description here

Where is Token

From GET access token API This is body of Response The 'message.token` is example of access token in JSON

{
    "success": true,
    "message": {
        "data": "User registered successfully",
        "token": "e9cee71ab932fde863338d08be4de9dfe39ea049bdafb342ce659ec5450b69ae"
    }
}

How to parse/save Token

In tests tab this script, extract the token from body response And save it into environment variable.

const jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable("access-token", jsonData.message.token);

How to use Token

In the POST call, Bearer token type and get token value from environment variable by {{variable_name}}

{{access-token}}

Demo

Mock 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('/api/me', (req, res) => {

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

    // Extract the base64 encoded credentials
    const base64Credentials = req.headers.authorization.split(' ')[1];
    const credentials = Buffer.from(base64Credentials, 'base64').toString('ascii');
    const [username, password] = credentials.split(':');

    // Check if username and password are valid
    if (username !== 'abcd' || password !== '1234') {
        res.status(401).json({ error: 'Unauthorized'});
        return;
    }

    // Hash the token
    accessToken = crypto.createHash('sha256').update(username+password).digest('hex');

    res.status(200).json({
        success: true,
        message: {
            data: 'User registered successfully',
            token: accessToken
        }
    });
});

// Update data API End point 
app.post('/api/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",
        data: "Top Secret Data"
    };
    res.json(updatedData); // Send the updated data in JSON format
});

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

Install dependencies

npm install express  cors crypto

Run server

node server.js

Postman call

Environment

enter image description here

Get access token

URL

GET {{baseUrl}}/api/me

Tests tab

const jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable("access-token", jsonData.message.token);

enter image description here

Result

enter image description here

Update Data

URL

POST {{baseUrl}}/api/data

with access token enter image description here

Result

enter image description here

401 Unauthorized Error

If I use wrong credential, will get 401 error. Mock server only works matched user name and password.

enter image description here