【问题标题】:Using both JWT and Passportjs同时使用 JWT 和 Passportjs
【发布时间】:2021-08-16 19:27:29
【问题描述】:

我正在开发 mern stack 应用程序,我使用 jwt 进行注册和使用 passportjs 进行社交登录。我目前正面临验证路线的问题。

这里是jwt和passportjs的Auth中间件:

     const jwt = require("jsonwebtoken")
    const Auth = async (req,res,next)=>{
        //if(req,headers)
        try {
            const token = req.headers.authorization.split(" ")[1]
            if(!token){
                return res.status(404).json({msg:"no token authorization"})
            }
            let decodeData
            
            decodeData = jwt.verify(token, process.env.JWT_SECRET)
            req.userId = decodeData.user.id
            next()
        } catch (error) {
            console.error(error.message);
            res.status(500).send("Server Error");
        }
    } 
    
    const passportAuth = (req,res,next)=>{
        if(!req.user){
            return res.status(404).json({msg:"user not loggged in"})
        }else{
            next()
        }
    }

module.exports = Auth
module.exports = passportAuth

登录用户可以创建帖子,但这里我有 jwt auth 和 passportauth。

如果在路由中同时使用 [Auth, passportAuth] 它将不起作用,因为用户必须使用谷歌登录或简单的注册注册。这是经过身份验证的路由代码

route.post("/",[auth,passportAuth], async(req,res)=>{
    const post = req.body
    try {
        const createpost = new Post({
            tags:post.tags,
            creator:post.creator,
            title: post.title,
            message: post.message,
            selectedFile: post.selectedFile,
            user:req.userId
        })
        await createpost.save()    
        res.json(createpost)
    } catch (error) {
        console.error(error.message);
        res.status(500).send("Server Error");
    }
})

那我该怎么办呢?

【问题讨论】:

  • route.post("/signup",[auth], async(req,res)=>{ ... }) route.post("/social-login",[passportAuth], async(req,res)=>{ ... })

标签: node.js reactjs express jwt passport.js


【解决方案1】:

也许不是返回错误响应,而是在响应上设置一些属性(类似于res.authenticated = true / res.authenticated = false)。然后有另一个中间件来检查是否设置了这个属性,如果它是false 或不存在,则只返回错误响应。你只需要确保这个中间件总是作为最后一个被调用(我现在不记得它在 express 中是如何工作的)。

附带说明 - 404 响应为 not found。对于缺少/错误身份验证的情况,您应该使用401

【讨论】:

    猜你喜欢
    • 2017-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-17
    • 2021-04-09
    • 2019-09-19
    • 1970-01-01
    相关资源
    最近更新 更多