Open In App

How to set authorization headers in Postman?

Last Updated : 25 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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:

  • Basic knowledge of Node and Express.
  • Node.js and npm installed on your machine.
  • Familiarity with JWT (JSON Web Tokens) concepts.
  • Basic Postman skills (creating collections and making new requests).

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:

Javascript




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:

  • Make a POST request to the `/login` endpoint to obtain a JWT token.
  • Set the request type to “POST” and enter the URL for the login endpoint (e.g., `http://localhost:3000/login`).
  • Add the necessary request body with valid credentials (username and password).

use the below credentials:

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

Step-1-Enter-the-url-of-login-endpoint-(3)-(1)

Step 2. Copy Token:

  • If successfully and get the response ( 200 ok )
  • Copy the JWT token from the response.

Screenshot-2566-12-15-at-122205

Step 3. Authorization in Postman:

  • Go to the headers tab in postman
  • Dropdown and add a key :” Authorization “ and token that you have copied as value
Key: Authorization
Value: your_token_here

Screenshot-2566-12-15-at-131722-(2)

Step 4: Hit Protected Endpoint:

  • Send the request again to the protected endpoint (`http://localhost:3000/protected`) and observe the response.

Screenshot-2566-12-15-at-132314

Output:

Untitled-design-(18)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads