Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

jwt

require('dotenv').config();
const jwt = require('jsonwebtoken');

function verifyJWT(req, res, next) {
    const authHeader = req.headers.authorization;
    if (!authHeader) {
        return res.status(401).send({ message: 'unauthorized access' });
    }
    const token = authHeader.split(' ')[1];
    jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (err, decoded) => {
        if (err) {
            return res.status(403).send({ message: 'Forbidden access' });
        }
        console.log('decoded', decoded);
        req.decoded = decoded;
        next();
    })
}


// this is inside run()
app.post('/login', async (req, res) => {
            const user = req.body;
            const accessToken = jwt.sign(user, process.env.ACCESS_TOKEN_SECRET, {
                expiresIn: '1d'
            });
            res.send({ accessToken });
})
Comment

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: "abhishek@gmail.com"
    }
    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")
})
Comment

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}));
});
Comment

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.
Comment

jwt

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

//output
base64(header + payload + signature);
Comment

jwt

jwt.sign(payload, secret, { expiresIn: expiry })

-------JWT Token Service-----------
import { JWT_SECRET } from "../config"
import jwt from "jsonwebtoken"
class jwtService {
   static sign(payload, expiry = "60s", secret = JWT_SECRET) {
        return jwt.sign(payload, secret, { expiresIn: expiry })
    }

    static verify(payload, secret = JWT_SECRET) {
        return jwt.verify(payload, secret)
    }
}

export default jwtService
Comment

jwt_token

curl -X POST 
  https://ims-na1.adobelogin.com/ims/exchange/jwt/ 
  -H 'Content-Type: multipart/form-data' 
  -F 'client_id=[KEY]' 
  -F 'client_secret=[CLIENT_SECRET]' 
  -F 'jwt_token=[JWT]'
Comment

jwt token

   // create token 
     const token = createToken({id:user._id}, '365d')


export const createToken = (payload, exp) => {
     return jwt.sign( payload, process.env.JWT_SECRET_KEY, {
          expiresIn:exp
     })
}
Comment

jwt_token

curl -X POST 
  https://ims-na1.adobelogin.com/ims/exchange/jwt/ 
  -H 'Content-Type: multipart/form-data' 
  -F 'client_id=[KEY]' 
  -F 'client_secret=[CLIENT_SECRET]' 
  -F 'jwt_token=[JWT]'
Comment

PREVIOUS NEXT
Code Example
Javascript :: mui react outlined input helperText 
Javascript :: vue is undefined vue 3 vue.use 
Javascript :: Upload a file using ExpressJS+Multer 
Javascript :: javascript data 
Javascript :: upload file on node js azure function 
Javascript :: multiple queries in node js 
Javascript :: send multipart form data axios with node js 
Javascript :: javascript debugging exercises 
Javascript :: json to string 
Javascript :: how to remove last element from array in javascript 
Javascript :: javascript search after user stops typing 
Javascript :: checkbox react 
Javascript :: javascript round to nearest integer 
Javascript :: 2d array javascript 
Javascript :: if else jsx 
Javascript :: remove storybook from project 
Javascript :: vuetify sass variables vue-cli 
Javascript :: double logical not javascript 
Javascript :: superagent set cookie 
Javascript :: overflowy 
Javascript :: mysql json 
Javascript :: creatable select react 
Javascript :: how to install moralis and react-moralis 
Javascript :: learn express 
Javascript :: confluent kafka nodejs 
Javascript :: what is asynchronous in javascript 
Javascript :: pass data between pages react 
Javascript :: react router path array 
Javascript :: getdata from fetch api into variable 
Javascript :: check last url in javascript 
ADD CONTENT
Topic
Content
Source link
Name
8+8 =