Code Monkey home page Code Monkey logo

mern-authb's Introduction

implementing JWT authentication in a Node.js + Express.js API:

Install Dependencies: First, make sure you have Node.js and npm installed. Then, create a new Node.js project and install the necessary packages: npm install express jsonwebtoken

Create an Authentication Middleware: You’ll need a middleware function to verify JWT tokens. Here’s a simple example: JavaScript

const jwt = require('jsonwebtoken');

function authenticateToken(req, res, next) { const authHeader = req.headers['authorization']; const token = authHeader && authHeader.split(' ')[1]; // Extract the token from the Authorization header

if (token == null) {
    return res.sendStatus(401); // Unauthorized
}

jwt.verify(token, 'your-secret-key', (err, user) => {
    if (err) {
        return res.sendStatus(403); // Forbidden
    }
    req.user = user; // Attach the user object to the request
    next();
});

} Generate Tokens on Login: When a user logs in, generate a JWT token and send it back to the client: JavaScript

const token = jwt.sign({ username: 'user123' }, 'your-secret-key', { expiresIn: '1h' }); res.json({ token });

Protect Routes: Apply the authenticateToken middleware to routes that require authentication: JavaScript

app.get('/protected-route', authenticateToken, (req, res) => { // Access the user object from req.user res.json({ message: 'Welcome to the protected route!' }); }, Client-Side Usage: In your client application (e.g., React, Angular, or Vue), store the token (usually in local storage) and include it in the Authorization header for authenticated requests. Remember to replace 'your-secret-key' with a strong, unique secret key for signing and verifying tokens. Also, consider using environment variables for sensitive information.

mern-authb's People

Contributors

dineshkumar-mb avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.