【问题标题】:how to secure routes in API and in client with next-auth如何使用 next-auth 保护 API 和客户端中的路由
【发布时间】:2021-02-20 19:51:24
【问题描述】:

我运行一个后端和一个前端,两者都由端口 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 中,这就是原因。

【问题讨论】:

    标签: express next.js next-auth


    【解决方案1】:

    您可以找到example of this in the next-auth-example project

    // 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。

    【讨论】:

      【解决方案2】:

      在 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
      
      })
      

      【讨论】:

      • 问题是关于下一个身份验证
      猜你喜欢
      • 2021-08-06
      • 2021-05-14
      • 2022-10-16
      • 2017-09-11
      • 2021-06-09
      • 1970-01-01
      • 1970-01-01
      • 2021-10-27
      • 2022-01-04
      相关资源
      最近更新 更多