无法使用带有 mongodb 的 typeorm 获取刷新令牌
Posted
技术标签:
【中文标题】无法使用带有 mongodb 的 typeorm 获取刷新令牌【英文标题】:Unable to get refresh token using typeorm with mongodb 【发布时间】:2021-02-21 20:58:52 【问题描述】:我试图通过刷新令牌获取访问令牌。使用 Typeorm 和 mongoDB。我正在传递 id,但 findone 没有从 DB 获取任何用户。如果我打印出完美的 ID。
刷新令牌代码:
app.post("/refreshToken", async (req, res) =>
// Read the incoming cookie
const token = req.cookies.jid;
// check if there is no token
if(!token) console.log("Case 1"); return res.send( ok: false, accessToken: "" )
// check if the token is not expired or valid
let payload: any = null;
try
payload = verify(token, process.env.REFRESH_TOKEN_SECRET!)
catch (error)
console.log(error);
return res.send( ok: false, accessToken: "" )
// If token exists, Read the UserID from payload as
// we have put userID while creating refresh token
// console.log("UID : " + payload.userId as ObjectID);
const user = await User.findOne( where: "_id": payload.userId )
console.log("USER : " + user);
// By any chance if there is no user found return no refresh token
if(!user) console.log("Case 2"); return res.send( ok: false, accessToken: "" )
// If there is an User; Return the refresh token
return res.send( ok: true, accessToken: createAccessToken(user) );
);
回复是:
USER : undefined
Case 2
这里是刷新和accesstoken的代码
import sign from 'jsonwebtoken';
import User from './entity/User';
export const createAccessToken = (user: User) =>
return sign( userId: user.id , process.env.ACCESS_TOKEN_SECRET!,
expiresIn: "15m"
)
// by adding ! it refers that the type is already defined
export const createRefreshToken = (user: User) =>
return sign(userId: user.id, , process.env.REFRESH_TOKEN_SECRET!,
expiresIn: "1d"
)
包.json:
"name": "server",
"version": "0.0.1",
"description": "Awesome project developed with TypeORM.",
"devDependencies":
"@types/bcryptjs": "^2.4.2",
"@types/cookie-parser": "^1.4.2",
"@types/express": "^4.17.8",
"@types/graphql": "^14.5.0",
"@types/jsonwebtoken": "^8.5.0",
"@types/node": "^14.14.6",
"nodemon": "^2.0.6",
"ts-node": "9.0.0",
"typescript": "4.0.5"
,
"dependencies":
"apollo-server-express": "^2.19.0",
"bcryptjs": "^2.4.3",
"cookie-parser": "^1.4.5",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"graphql": "^15.4.0",
"jsonwebtoken": "^8.5.1",
"mongodb": "^3.0.8",
"reflect-metadata": "^0.1.13",
"type-graphql": "^1.1.1",
"typeorm": "0.2.28"
,
"scripts":
"start": "nodemon --exec ts-node src/index.ts"
【问题讨论】:
【参考方案1】:根据typeorm的文档,我猜你使用的查询条件不正确。 请尝试以下操作:
const user = await repository.findOne(payload.userId); // find by id
//or
const user = await repository.findOne("_id": payload.userId);
【讨论】:
以上是关于无法使用带有 mongodb 的 typeorm 获取刷新令牌的主要内容,如果未能解决你的问题,请参考以下文章
NestJS TypeORM mongodb 在数组列中查找不起作用
使用带有 TypeOrm 的 NestJS 连接 MySQL 数据库时出现问题
typeorm createConnection 即使在带有 PG 的 MacOS 上使用 Await 也会返回 Pending