小编sok*_*ida的帖子

使用 Next.js 中间件的 Next auth v4

我使用 Next.js 和 next auth v4 进行凭据身份验证。

我想要做的是在中间件中为我的 API 调用添加全局验证,以便在 API 调用会话之前进行测试。如果会话不为空,则调用必须成功通过,否则如果会话为空,则处理未经授权的错误消息并重定向到登录页面。

我还想为登录页面和其他不需要检查身份验证的页面添加受保护的路由和不受保护的路由。

这是我的代码: [...nextauth].js

import NextAuth from "next-auth"
import CredentialsProvider from "next-auth/providers/credentials";
import api from './api'

export default NextAuth({
    providers: [
        CredentialsProvider({
          name: "Credentials",
          async authorize(credentials, req) {
            const {username,password} = credentials    
            const user = await api.auth({
                username,
                password,
            })

            if (user) {
              return user
            } else {
              return null
              
            }
          }
        })
    ],
    callbacks: {
        async jwt({ token, user, account }) {
            let success = user?.id > 0 …
Run Code Online (Sandbox Code Playgroud)

javascript authorization next.js next-auth

7
推荐指数
1
解决办法
3万
查看次数

标签 统计

authorization ×1

javascript ×1

next-auth ×1

next.js ×1