Este grupo de trabajo ha pasado horas buscando para darle espuestas a tu pregunta, te regalamos la solución por eso nuestro deseo es serte de mucha apoyo.
Ejemplo 1: ejemplo de token jwt en el nodo js
functionauthenticateToken(req, res, next)// Gather the jwt access token from the request headerconst authHeader = req.headers['authorization']const token = authHeader && authHeader.split(' ')[1]if(token ==null)return res.sendStatus(401)// if there isn't any token
jwt.verify(token, process.env.ACCESS_TOKEN_SECRETasstring,(err:any, user:any)=>console.log(err)if(err)return res.sendStatus(403)
req.user = user
next()// pass the execution off to whatever request the client intended)
Ejemplo 2: token de actualización jwt
/**
@description for module commonjs
*/// JWT MIDDLEWAREconst jwt =require('jsonwebtoken')const message =require('../utils/util.message')module.exports=(req, res, next)=>tryconst tokenHeader = req.headers.authorization.split('Bearer ')[1]const decoded = jwt.verify(tokenHeader, process.env.ACCESS_TOKEN_SECRET)
req.user = decoded
next()catch(err)next(httpError(401))// ROUTE LOGIN
app.get('/protect', authJwt,(req, res)=>console.log(req.user)
res.send('aim in proteced route'))
app.post('/login',(req, res)=>const bodyPayload =
id: Date.now(),
username: req.body.username
const token =signAccessToken(res, bodyPayload)return res.status(200).json(token))
app.post('/refresh-token',(req, res)=>const refreshToken =signRefreshToken(req)return res.status(200).json(refreshToken))// JWT HELPERconst jwt =require('jsonwebtoken')const message =require('../utils/util.message')
exports.signAccessToken=(res, payload)=>tryif(payload)const accessToken = jwt.sign(...payload , process.env.ACCESS_TOKEN_SECRET, expiresIn:'1d')const refreshToken = jwt.sign(...payload , process.env.REFRESH_TOKEN_SECRET, expiresIn:'90d')
res.cookie('refreshToken',`$refreshToken`, maxAge:86400*90, httpOnly:true)return accessToken, refreshToken catch(err)message(
response: res,
statusCode:401,
method: req.method,
message:'Unautorization')
exports.signRefreshToken=(req)=>tryconst getToken = req.cookies.refreshToken
if(getToken)const id, username = jwt.verify(getToken, process.env.REFRESH_TOKEN_SECRET)const accesssToken = jwt.sign( id, username , process.env.ACCESS_TOKEN_SECRET, expiresIn:'90d')return accesssToken catch(err)message(
response: res,
statusCode:401,
method: req.method,
message:'Unautorization')
Ejemplo 3: token de actualización jwt
import Request, Response from'express'import jwt, Secret, SignOptions from'jsonwebtoken'import Base64 from'js-base64'import UsersDTO from'../dto/dto.users'constACCESS_TOKEN_SECRET: Secret = process.env.ACCESS_TOKEN_SECRETconstREFRESH_TOKEN_SECRET: Secret = process.env.REFRESH_TOKEN_SECRETexportconstsignAccessToken=()=>(res: Response, payload: UsersDTO, options: SignOptions):string|any=>if(!payload)returnnullelseconst accessToken:string= jwt.sign(...payload ,ACCESS_TOKEN_SECRET,...options )const refreshToken:string= jwt.sign(...payload ,REFRESH_TOKEN_SECRET, expiresIn:'90d')const encodedAccessToken:string= Base64.encode(accessToken)const encodedRefreshToken:string= Base64.encode(refreshToken)
res.cookie('refreshToken',`$encodedRefreshToken`, maxAge:86400*90, httpOnly:true)return accessToken: encodedAccessToken, refreshToken: encodedRefreshToken exportconstverifySignAccessToken=()=>(token:string):string|any=>if(!Base64.isValid(token))returnnullelseany= jwt.verify(decodedToken,ACCESS_TOKEN_SECRET)return decoded
exportconstsignRefreshToken=()=>(req: Request):string|any=>const getToken:string= req.cookies.refreshToken
if(!Base64.isValid(getToken)&&!getToken)returnnullelseany= jwt.verify(decodedToken,REFRESH_TOKEN_SECRET)const accessToken:string= jwt.sign( user_id: user_id, email: email ,ACCESS_TOKEN_SECRET,
expiresIn:'90d')const encodedAccessToken:string= Base64.encode(accessToken)return encodedAccessToken
Te mostramos reseñas y calificaciones
Finalizando este artículo puedes encontrar las crónicas de otros creadores, tú además tienes el poder mostrar el tuyo si lo crees conveniente.
¡Haz clic para puntuar esta entrada!
(Votos: 0 Promedio: 0)