当前位置: 首页>>代码示例>>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;未经允许,请勿转载。