NextAuth和中间件-停留在登录页面,登录后不会重定向,为什么我没有代币?

mnowg1ta  于 2023-04-30  发布在  其他
关注(0)|答案(1)|浏览(157)

从我实现中间件开始。ts,用户不会被重定向到callbackUrl,而是会停留在签名页面上。
我遵循文档,并在middleware.ts中开始使用此

export { default } from "next-auth/middleware";
export const config = { matcher: ["/dashboard","/dashboard/:path*"] };

但我正面临着我提到的问题。这不能让我在我的应用程序沿着。
然后我想我可以在这个文件中定义更多:

import { withAuth } from "next-auth/middleware";
import { NextResponse } from "next/server";

export default withAuth(
    function middleware(req) {
        console.log("🚀 ~ file: middleware.ts:7 ~ middleware ~ req:", req);
        // return Nextreponse
        // console.log('middleware nextauth token', req.nextauth.token);
        // return NextResponse.rewrite(new URL('/dashboard', req.url));
    },
    {
        callbacks: {
            authorized: ({ token, req }) => {
                // console.log("🚀 ~ file: middleware.ts:16 ~ req.cookies:", req.cookies);
                console.log("🚀 ~ file: middleware.ts:17 ~ token:", token);
                if (token) { return true; }
                // else if (req.cookies) return true;
                return false;
            },
        }
    }

);
export const config = { matcher: ["/dashboard","/dashboard/:path*"] };

在回调中,令牌总是返回null。我不明白为什么。我只能得到请求。cookie,并认为如果它们存在,并且如果我可以返回true,我的流将继续进行,并且我将能够到达受保护的路由。
1.为什么代码的第一个版本不允许我的应用流程继续?
1.为什么我没有从callbacks.authorized获得令牌?
1.我假设只是检查是否存在cookie,是不够的一个安全的方式来保护一个页面,对不对?
下面是我在[...nextauth].ts中的代码

import NextAuth, { NextAuthOptions } from "next-auth";
import GithubProvider from "next-auth/providers/github";
import CredentialsProvider from "next-auth/providers/credentials";
import getDbCollection from "../../../../lib/getCollection";
import { UserData } from "../../../types/users";
import { useUserStore } from "../../../stores/user";
import { JWT } from "next-auth/jwt";
import { redirect } from "next/dist/server/api-utils";

export const authOptions: NextAuthOptions = {
    // Configure one or more authentication providers
    providers: [
        GithubProvider({
            clientId: process.env.GITHUB_ID as string,
            clientSecret: process.env.GITHUB_SECRET as string,
        }),
        // ...add more providers here
        CredentialsProvider({
            // The name to display on the sign in form (e.g. "Sign in with...")
            name: "Credentials",
            // `credentials` is used to generate a form on the sign in page.
            // You can specify which fields should be submitted, by adding keys to the `credentials` object.
            // e.g. domain, username, password, 2FA token, etc.
            // You can pass any HTML attribute to the <input> tag through the object.
            credentials: {
                email: { label: "Email", type: "text", placeholder: "user@example.ca" },
                password: { label: "Password", type: "password" }
            },
            async authorize(credentials, req) {
                // const setUserInfo = useUserStore(state => state.setUserInfo);
                console.log("🚀 ~ file: [...nextauth].ts:25 ~ authorize ~ credentials:", credentials);

                // Add logic here to look up the user from the credentials supplied. We will check against the DB see if the user's exist.
                const collection = await getDbCollection("users");
                // const user = { id: "1", name: "J Smith", email: "jsmith@example.com" };
                const { email, password } = credentials as {
                    email: string;
                    password: string;
                };
                try {
                    const user = await collection.findOne({ $and: [{ email: credentials?.email }, { pwd: credentials?.password }] }) as UserData;
                    console.log("🚀 ~ file: [...nextauth].ts:38 ~ authorize ~ user:", user);

                    if (!user
                        // || user.pwd !== credentials?.password
                    ) {
                        // If you return null then an error will be displayed advising the user to check their details.
                        throw new Error("Invalid Login");
                        // return null;
                    }
                    // else {
                    // Maybe not needed with session info
                    // setUserInfo(user);
                    // Any object returned will be saved in `user` property of the JWT
                    return {
                        id: user?._id as string,
                        name: user.name,
                        email: user.email,
                        role: user.role,
                        domain: user.domain
                        // ...user
                    };

                    // You can also Reject this callback with an Error thus the user will be sent to the error page with the error message as a query parameter
                    // }
                } catch (error) {
                    console.log("🚀 ~ file: [...nextauth].ts:58 ~ authorize ~ error:", error);
                    // throw new Error("Invalid Login");
                    return null;
                }
            },
        })
    ],
    // TODO: try without?
    session: {
        strategy: 'jwt'
    },
    callbacks: {
        async jwt({ token, user }: { token: JWT, user?: any | UserData; }) {
            console.log("🚀 ~ file: [...nextauth].ts:78 ~ jwt ~ token:", token);
            console.log("🚀 ~ file: [...nextauth].ts:78 ~ jwt ~ user:", user);
            // update token
            if (user?.role) {
                token.role = user.role;
            }
            if (user?.domain) {
                token.domain = user.domain;
            }
            // return final token
            return token;
        },
        async session({ session, token, user }: { session: any, token: JWT, user: any; }) {
            if (token.role) (session.user.role = token.role);
            if (token.domain) session.user.domain = token.domain;
            return session;
        },

        // async redirect({ url, baseUrl }) {
        //     return baseUrl + '/dashboard/beers';
        // },
    },
};

export default NextAuth(authOptions);
2mbi3lxu

2mbi3lxu1#

只要确保
1.你有NEXTAUTH_SECRET & NEXTAUTH_URL在你的.env文件
1.秘密:过程。env.NEXTAUTH_SECRET在[...nextauth]。js阅读正确的值
1.中间件ts回调条件适用于当前用户

相关问题