如何使用next-auth

问题描述

我运行一个后端和一个前端,两者都是通过在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时,但是我该如何让这2个人互相交谈

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

请记住,我分开运行后端和前端,因为我的productionbuild在docker中,这就是为什么。

解决方法

在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

})
,

您可以找到一个http://localhost:8153/api.rsc/FBI_dbo_PERSON(per_id=10001)

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

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...