0

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

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

因此,该应用程序可以正常获取这些路线。现在我需要你的帮助。我已经添加了 next-auth 所以在前端我可以

const [ session, loading ] = useSession();

做类似的事情

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

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

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

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

4

2 回答 2

0

您可以在 next-auth-example 项目中找到这样的示例

// 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.' })
  }
}

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

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

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

于 2020-11-10T12:26:23.993 回答
-1

在 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

})
于 2020-11-09T09:26:18.857 回答