Skip to content

Latest commit

 

History

History
67 lines (51 loc) · 1.49 KB

README.md

File metadata and controls

67 lines (51 loc) · 1.49 KB

NODE-AUTH-CSRF

node-auth-csrf is a lightweight library designed for csrf protection.

INSTALLATION

You can install node-auth-csrf via npm:

npm install node-auth-csrf

USAGE

To integrate node-auth-csrf into your express application, follow these simple steps:


# Functions

const { csrfProtection } = require('node-auth-csrf');

csrfProtection - used to initialize node-auth-csrf

generateToken - used for generating token

EXAMPLE

const express = require('express');
const { csrfProtection } = require('node-auth-csrf');

const app = express();

app.use(csrfProtection(process.env.CSRF_SECRET));
app.get("/csrf-token", (req, res) => {
    const csrfToken = req.csrfProtection.generateToken();
    res.json({ csrfToken });
});

app.get('/protected', (req, res) => {
    res.send(req.user);
});

app.listen(3000, () => {
    console.log('Server is running on port 3000');
});

Here all POST, PUT and DELETE route will be protected by node-auth-csrf

`x-csrf-token` must exist on the header of the request to be able to authorize the request.
headers: {
  'x-csrf-token': 'generated token'
}

GUIDES

You can also use csrfProtection on specific route or route group if you don't want to put it globally

app.get('/protected', csrfProtection(process.env.CSRF_SECRET), (req, res) => {
    res.send(req.user);
});

OR

app.use('/protected', csrfProtection(process.env.CSRF_SECRET), protectedRoutes);