Answers for "jwt"

13

jwt

// index.js 

const express = require('express');
const jwt = require('jsonwebtoken');

const app = express();

// generate token for another API to use in req.header
app.post('/login', (req, res) => {
    const user = {
        id: 1,
        username: 'abhishek',
        email: "[email protected]"
    }
    let token = jwt.sign({ user: user }, 'shhhhh');
    res.send(token);
})

// verifyToken is a function that is used for check in API that token exist or not
// it can be put in between n number of API to check that authoriZed user loggedin or not.
app.get('/api', verifyToken, (req, res) => {
    try {
        jwt.verify(req.token, 'shhhhh', (error, authData) => {
            if (error) {
                res.send("not logged in")
            }
            res.json({
                message: "post Created",
                authData
            })
        })
    } catch (error) {
        res.send(error)
    }
})

// This funtion is middleware. 
function verifyToken(req, res, next) {
    try {
        const bearerHeader = req.headers['authorization'];
        if (typeof bearerHeader !== 'undefined') {
            const bearerToken = bearerHeader.split(' ')[1];
            req.token = bearerToken;
            next();
        }
        else {
            res.send("Not logged-in")
        }
    }
    catch {
        res.send("something went wrong")
    }
}

app.listen(3000, () => {
    console.log("server is runing")
})
Posted by: Guest on February-18-2021
2

jwt

// Import the module
import jwt from "jsonwebtoken";

// You will need a SECRET KEY to create the token, I would recommend to store
// it inside a .env file. For this example though, I will store it a variable.
const secretKey = "ro8BS6Hiivgzy8Xuu09JDjlNLnSLldY5";

// Data that will be stored inside the token. In this example we will store the
// name and the role of each user
var payload = {
  name: "Roger",
  role: "Admin",
};

// Generate the token
const token = jwt.sign(payload, secretKey);

// The token is ready to send to the client. REST API example:
res.status(200).send(JSON.stringify({ accessToken: token }));

// Client will store your token the following way: "Bearer " + token

// How to decode a user's token and get its payload. REST API example:
const authHeader = req.headers["authorization"]; // Client will send you back the token inside request's authorization header

const token = authHeader && authHeader.split(" ")[1];
if (token == null) {
  res.status(401).send(); // Unauthorized
}

var decoded = jwt.verify(token, secretKey, (err, user) => {
  if (err) {
    res.status(403).send(); // Forbidden
  }
});

// Do what you want to do with the data

// Remember that this is for learning purposes only. You should create FUNCTIONS
// AND MIDDLEWARES so you do not repeat code.
Posted by: Guest on September-09-2021
4

jwt

let jwt = require('jsonwebtoken');

const SUPER_SECRET_TOKEN = "My_Secret_Token";

server.post('/',(req,res)=>{
    res.setHeader('Content-Type', 'application/json');
    var token = jwt.sign({message: "Hello"}, SUPER_SECRET_TOKEN, { expiresIn: '5m' , noTimestamp: true });
    var result = jwt.verify(token, SUPER_SECRET_TOKEN);
    res.end(JSON.stringify({error: false, data: result}));
});
Posted by: Guest on June-19-2020
3

jwt

JSON Web Token is an Internet standard for creating data with optional
signature and/or optional encryption whose payload holds JSON that asserts
some number of claims.

The tokens are signed either using a private secret or a public/private key.
Posted by: Guest on June-19-2020
0

jwt

HMACSHA256(
  base64UrlEncode(header) + "." +
  base64UrlEncode(payload),
  
) secret base64 encoded
Posted by: Guest on June-15-2020
1

jwt

//initial
header(metadata)
payload(data)
signature( oneWayEncryption( header + payload + secretkey ) )

//output
base64(header + payload + signature);
Posted by: Guest on June-15-2021

Browse Popular Code Answers by Language