如何使用next-auth在API和客户端中保护路由



我运行一个后端和一个前端,两者都由express提供服务,后端在端口8080上,前端在端口80上。

/api/route1        returns 200ok with json
/api/route2        returns 200ok with json 

因此,该应用程序可以很好地获取这些路线。现在来谈谈我需要你帮助的事情。我已经添加了下一个身份验证,所以在前端我可以

const [ session, loading ] = useSession();

做一些类似的事情

{!session && <p>You are not logged in</p>}

这是有效的,但我还没有弄清楚如何保护到API的路由。我想在前端和后端保护路由1和路由2。我想当我登录时,需要将令牌传递给API,但我如何才能让这两个互相交谈

/api/route1        returns 200ok with json
/api/route2        returns 200ok with json 

请记住,我分别运行后端和前端,因为我的生产构建在docker中,这就是为什么。

您可以在下一个auth示例项目中找到这样的示例

// pages/api/examples/protected.js
import { getSession } from 'next-auth/client'
export default async (req, res) => {
const session = await getSession({ req })
if (session) {
res.send({ content: 'This is protected content. You can access this content because you are signed in.' })
} else {
res.send({ error: 'You must be sign in to view the protected content on this page.' })
}
}

如果会话对象存在(即不为null(,则意味着它们具有有效的会话令牌(如果使用数据库会话(或有效的签名JSON Web令牌(如果采用JWT会话(。

在这两种情况下,都会检查会话令牌以确保其有效且未过期。

当以这种方式使用时,请求对象req被传递到getSession()调用,以便可以检查和验证包含会话令牌的cookie。

在Node中处理受保护路由的方法是使用中间件。

所以,假设您有一个在数据库中添加员工工资的途径,所以很明显,这样的途径需要一个经过身份验证的管理员,对吗?

  • 因此,您可以制作一个中间件功能,如下面的简单功能
const validateAdminCookie = (req, res, next)=>{
//Here you then write all your logic on how you validate admin

//Now you will have conditonals here that:
if (!validatedCookie){
return res.status(400).json({msg:'Not authorized'})
}
next();
}
  • 因此,现在该函数是您将在路由中传递的函数,因此它将首先执行,当用户是有效的经过身份验证的管理员时,next()将把该用户推到他们试图访问的主路由,否则如果未通过身份验证,则会返回一条消息,表明他们未经过身份验证

现在如何传递此中间件如下所示:

router.post('/api/admin-update-salaries',validateAdminCookie, (req, res)=>{
//Now that **validateAdminCookie** will execute first and if all
//checks out then user will be pushed down to the main part
//that is this route here
})

最新更新