當前位置: 首頁>>代碼示例>>TypeScript>>正文


TypeScript jsonwebtoken.verify函數代碼示例

本文整理匯總了TypeScript中jsonwebtoken.verify函數的典型用法代碼示例。如果您正苦於以下問題:TypeScript verify函數的具體用法?TypeScript verify怎麽用?TypeScript verify使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了verify函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的TypeScript代碼示例。

示例1: return

        return(req, res, next) => {

          if (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') {
            const token = req.headers.authorization.split(' ')[1];

            const allowAll = true;
            const allowedOrigins = ['http://localhost:3000', 'http://localhost:4200', 'http://www.resucitoapp.com'];
            if (allowAll || allowedOrigins.indexOf(req.header('Origin')) > -1) {
                if (allowAll) {
                  res.setHeader('Access-Control-Allow-Origin', '*');
                } else {
                  res.setHeader('Access-Control-Allow-Origin', req.header('Origin'));
                }
                res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
                res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
                res.setHeader('Access-Control-Allow-Credentials', true);
            } else {
                return res.status(401).json('Origen no permitido');
            }

            jwt.verify(token, 'my-secret', (err, payload) => {
              if (!err) {
                // confirm identity and check user permissions
                req.payload = payload;
                next();
              } else {
                 return res.status(403).json(err);
              }
            });
          } else {
            return res.status(401).json('El token de acceso no es válido.');
          }
        };
開發者ID:camposmiguel,項目名稱:rzeszow2018,代碼行數:33,代碼來源:auth.middleware.ts

示例2: async

export const getUser = async (
  apiSecret: string,
  prisma: Prisma,
  req: IncomingMessage,
): Promise<NexusGenFieldTypes['User'] | null> => {
  const { authorization } = req.headers;
  if (authorization == null) return null;
  const token = authorization.replace('Bearer ', '');

  let decoded = {};
  try {
    decoded = jwt.verify(token, apiSecret);
  } catch (error) {
    if (error.name !== 'JsonWebTokenError') {
      // eslint-disable-next-line no-console
      console.log(error);
    }
    return null;
  }

  const hasUserId = (decoded: any): decoded is JsonWebTokenPayload =>
    'userId' in decoded;
  if (!hasUserId(decoded)) return null;

  const user = await prisma.user({ id: decoded.userId });
  if (user == null) return null;

  // Do not fetch user webs, we don't need it. getUser is used only for auth.
  return { ...user, webs: [] };
};
開發者ID:este,項目名稱:este,代碼行數:30,代碼來源:getUser.ts

示例3: function

    router.get('/refresh_token/:token', function(req, res) {
        jwt.verify(req.params.token, config.token_secret, function(err, decoded) {
            if (err) {
                res.status(401).json({ error: 'Unauthorized', message: 'failed to authenticate token' });
                return;
            }



            // create the payload for the token
            let payload = decoded; // reuse the payload
            delete payload.exp; // remove the exp date from the payload
            let options = {
                expiresIn: config.time_until_token_expiration
            };

            // create a token and send it to the user
            let token = jwt.sign(payload, config.token_secret, options, function(err, token) {
                if (err) {
                    res.status(500).json({ error: 'Internal Server Error', message: 'error generating token', username: req.body.username });
                    return;
                }

                let exp_date = new Date();
                exp_date.setSeconds(exp_date.getSeconds() + config.time_until_token_expiration);

                res.status(200).json({ message: 'here is a new token', token: token, exp: exp_date });
            });
        });
    });
開發者ID:,項目名稱:,代碼行數:30,代碼來源:

示例4: function

userRoutes.use(function(req, res, next) {

  // check header or url parameters or post parameters for token
  var token = req.headers['authorization'];
  // decode token
  if (token) {
    var token = token.replace('Bearer ', '')
    // verifies secret and checks exp
    jwt.verify(token, config.secret, function(err, decoded) {
      if (err) {
        return res.json({ success: false, message: 'Failed to authenticate token.' });
      } else {
        // if everything is good, save to request for use in other routes
        //req.decoded = decoded;
        next();
      }
    });

  } else {

    // if there is no token
    // return an error
    return res.status(403).send({
      success: false,
      message: 'No token provided.'
    });

  }
});
開發者ID:ieltxu13,項目名稱:ag2print-server,代碼行數:29,代碼來源:userRoutes.ts

示例5: authenticate

 export function authenticate(req: express.Request, res: express.Response) {
         if(req.header('Authorization')){
                 let token = req.header('Authorization');
                 jwt.verify(token, config.JwtStrategy.secretOrKey, {}, function (err: any, userInfo: any) {
                  if(err) throw err;
                 if(userInfo === null) {
                          res.send({
                                 isSuccess: false,
                                 msg: 'token verification is failed!'
                         })
                 }
                 res.send({
                         isSuccess: true,
                         userName: userInfo.username
                 })
         })
         }else{
                 res.send({
                         isSuccess: false,
                         msg: 'There is no token!'
                 })
         }
         
         
        
 }
開發者ID:jcdby,項目名稱:SuwonCMIAPIServer,代碼行數:26,代碼來源:userController.ts

示例6: function

var middleware = function (req, res, next) {
    let token = req.headers.authorization;
    if (token !== undefined) {
        let jwtoken = token.split(" ")[1];
        jwt.verify(jwtoken, Config.secret, (error, decoded) => {
            if (error) {
                res.locals.loggedIn = false;
                res.locals.user = {};
                res.locals.role = "";
                next();
            } else {
                //good, authenticated request
                delete decoded.user.password;

                res.locals.loggedIn = true;
                res.locals.user = decoded;
                res.locals.user_id = decoded.user._id;
                res.locals.role = res.locals.user.user.role;

                next();
            }
        });
    } else {
        res.locals.loggedIn = false;
        res.locals.user = {};
        res.locals.role = "";
        next();
    }
};
開發者ID:BartoszSiemienczuk,項目名稱:teamsuite,代碼行數:29,代碼來源:auth.middleware.ts

示例7: Promise

        return new Promise(async (resolve, reject) => {
            if (!p.token) {
                reject("You must provide a valid token");
                return;
            }
            let options: any = { "issuer": this.issuer.value };

            try {
                let key = this.secretKey.value;
                //options.algorithms=[ALGORITHM];

                jwt.verify(p.token, key, options, (err, payload) => {
                    if (err) {
                        reject(err);
                    }
                    else {
                        const token = payload.value;
                        resolve(token);
                    }
                });
            }
            catch (err) {
                reject({ error: err, message: "Invalid JWT token" });
            }
        });
開發者ID:workfel,項目名稱:vulcain-corejs,代碼行數:25,代碼來源:tokenService.ts

示例8: next

apiRoutes.use((req:any, res, next) => {

  // check header or url parameters or post parameters for token
  var token = req.body.token || req.query.token || req.headers['x-access-token'];

  // decode token
  if (token) {

    // verifies secret and checks exp
    jwt.verify(token, app.get('superSecret'), (err, decoded) => {      
      if (err) {
        return res.json({ success: false, message: 'Failed to authenticate token.' });    
      } else {
        // if everything is good, save to request for use in other routes
        req.decoded = decoded;    
        next();
      }
    });

  } else {

    // if there is no token
    // return an error
    return res.status(403).send({ 
        success: false, 
        message: 'No token provided.' 
    });
    
  }
});
開發者ID:krishnavteja,項目名稱:node-auth,代碼行數:30,代碼來源:server.ts

示例9: function

export = function (req, res, next) {

  // check header or url parameters or post parameters for token
  var token = req.body.token || req.query.token || req.headers['x-access-token'];

  // decode token
  if (token) {

    // verifies secret and checks exp
    jwt.verify(token, config.JWTSECRET, function (err, decoded) {
      if (err) {
        return res.status(401).send({
          success: false,
          message: 'Failed to authenticate token.'
        });
      } else {
        // if everything is good, save to request for use in other router
        req.decoded = decoded;
        next();
      }
    });

  } else {

    // if there is no token
    // return an error
    return res.status(403).send({
      success: false,
      message: 'No token provided.'
    });

  }
};
開發者ID:pmcalabrese,項目名稱:Express-Typescript-boilerplate,代碼行數:33,代碼來源:authenticate.ts

示例10: decodeJwt

export async function decodeJwt(token:string) {

    const payload = await jwt.verify(token, RSA_PUBLIC_KEY);

    console.log("decoded JWT payload", payload);

    return payload;
}
開發者ID:bala1074,項目名稱:angular-security-course,代碼行數:8,代碼來源:security.utils.ts

示例11: getUserFromToken

 getUserFromToken(token: string = '') {
     try {
         const user = jwt.verify(token, secret) as IUserDto;
         return user;
     } catch (err) {
         return null;
     }
 }
開發者ID:ravendyg,項目名稱:photo-tl-server,代碼行數:8,代碼來源:utils.ts

示例12: Promise

 new Promise((resolve, reject) => {
     jwt.verify(request.query.token, JWT_SECRET, {ignoreExpiration: true}, (error, decoded) => {
         if (error) {
             return reject(error)
         }
         resolve(decoded)
     });
 }).then((decoded: {user: string}) => {
開發者ID:rajivnarayana,項目名稱:expressts-jwt,代碼行數:8,代碼來源:index.ts

示例13: checkToken

 checkToken(req, res, next) {
   try {
     jwt.verify(req.body.token, this.privateKey);
     this.successResponse(res);
   } catch(exp) {
     next(new UnauthorizedError("Invalid token"));      
   }
 }
開發者ID:kaka3004,項目名稱:cms,代碼行數:8,代碼來源:auth-controller.ts

示例14: verifyToken

 public verifyToken(token: string, next: (err: Error, payload: any) => void) {
     let options: jwt.SignOptions = {
         expiresIn: api.helpers.Config.settings.expiration_jwt_minutes * 60,
         issuer: 'tforex-gateway',
         jwtid: 'uniqueId',
     };
     jwt.verify(token, api.helpers.Config.settings.jwt_secret, options, next);
 }
開發者ID:arandehkharghani,項目名稱:tforex-gateway,代碼行數:8,代碼來源:jwt-token.service.ts

示例15: getUserId

export function getUserId(context: Context) {
  const Authorization = context.request.get('Authorization')
  if (Authorization) {
    const token = Authorization.replace('Bearer ', '')
    const verifiedToken = verify(token, APP_SECRET) as Token
    return verifiedToken && verifiedToken.userId
  }
}
開發者ID:markthink,項目名稱:prisma-examples,代碼行數:8,代碼來源:utils.ts


注:本文中的jsonwebtoken.verify函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。