Open In App

How to set authorization headers in Postman?

Web application security is vital, and JSON Web Tokens (JWT) play a key role in authentication and route protection. In this article we will learn how to create a secure backend with Node and Express using JWT, and then we will demonstrate how to set authorization headers in Postman for effective API testing.

Note: We will first create a backend server so that in the latter steps we will know how to set “Authorization header” in Postman.

Prerequisites:

Steps to create Backend with Node and Express:

Step 1: Create a project directory and initialize it:



mkdir jwt-auth-example

Step 2: Change the directory to jwt-auth-example:

cd jwt-auth-example

Step 3: Initialize the npm:



npm init -y

Step 4: Install Dependencies Express.js and jsonwebtoken:

npm install express jsonwebtoken

Step 5: Implement JWT Authentication by Creating a file named `app.js` and implement the code below:




const express = require("express");
const jwt = require("jsonwebtoken");
const bodyParser = require("body-parser");
 
const app = express();
const PORT = 3000;
const SECRET_KEY = "your_secret_key"; // Replace with a strong secret key
 
app.use(bodyParser.json());
 
// Example User Model
const users = [{ id: 1, username: "john_doe", password: "password123" }];
 
// Middleware for JWT Verification
const verifyToken = (req, res, next) => {
    // Extract the token from the Authorization header
    const token = req.header("Authorization");
 
    // Check if the token is missing
    if (!token) {
        return res
            .status(401)
            .json({ message: "Access denied. Token missing." });
    }
 
    try {
        // Verify the token and decode its payload
        const decoded = jwt.verify(token, SECRET_KEY);
 
        // Attach the user information to the request
        // for use in the protected route
        req.user = decoded;
 
        // Move to the next middleware or route handler
        next();
    } catch (error) {
        // Handle invalid tokens
        res.status(401).json({ message: "Invalid token" });
    }
};
 
// Protected Route
app.get("/protected", verifyToken, (req, res) => {
    // Send a JSON response with a message
    // and the user information from the token
    res.json({ message: "This is a protected route!", user: req.user });
});
 
// Login Route
app.post("/login", (req, res) => {
    const { username, password } = req.body;
 
    // Check if user credentials are valid by
    // finding a user in the 'users' array
    const user = users.find(
        (u) => u.username === username && u.password === password
    );
 
    // If user is not found, respond with an error
    if (!user) {
        return res.status(401).json({ message: "Invalid credentials" });
    }
 
    // Generate a JWT with user information and
    // send it as a response upon successful authentication
    const token = jwt.sign(
        { userId: user.id, username: user.username },
        SECRET_KEY
    );
    res.json({ token });
});
 
// Start the server
app.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`);
});

Step 6: Start the server

node app.js

Steps to Hit Endpoints Using Postman:

Step 1: Login Endpoint:

use the below credentials:

{
"username":"john_doe",
"password":"password123"
}

Step 2. Copy Token:

Step 3. Authorization in Postman:

Key: Authorization
Value: your_token_here

Step 4: Hit Protected Endpoint:

Output:


Article Tags :