本文整理汇总了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.');
}
};
示例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: [] };
};
示例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 });
});
});
});
示例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.'
});
}
});
示例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!'
})
}
}
示例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();
}
};
示例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" });
}
});
示例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.'
});
}
});
示例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.'
});
}
};
示例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;
}
示例11: getUserFromToken
getUserFromToken(token: string = '') {
try {
const user = jwt.verify(token, secret) as IUserDto;
return user;
} catch (err) {
return null;
}
}
示例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}) => {
示例13: checkToken
checkToken(req, res, next) {
try {
jwt.verify(req.body.token, this.privateKey);
this.successResponse(res);
} catch(exp) {
next(new UnauthorizedError("Invalid token"));
}
}
示例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);
}
示例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
}
}