有人在 next.js 中用过 nextAuth 吗?想问个问题 - V2EX
V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
philsky28
V2EX    问与答

有人在 next.js 中用过 nextAuth 吗?想问个问题

  •  1
     
  •   philsky28 2023-01-19 14:25:57 +08:00 1979 次点击
    这是一个创建于 994 天前的主题,其中的信息可能已经有所发展或是发生改变。

    我想实现一下 SSR 功能,具体流程是这样,先是在登录页登录,然后调用 nextAuth 的 signin 方法,登录成功 token 会放到 session 里,之后跳转首页调用GetServerSideProps,里面发起 fetch 拿数据。 但是在第一次进入首页时发现GetServerSideProps中利用 nextAuth 的 apigetSession获取的 session 是 null ,组件内部能获得,并且 terminal 报错message: 'decryption operation failed'。但是一刷新后 session 又能正常获得了,控制台也没有报错,不知道有没有人遇到过和我一样的情况?代码如下:

    // [...nextauth].ts export default NextAuth({ session: { strategy: "jwt", }, providers: [ CredentialsProvider({ name: "xxx", id: "credentials", credentials: { phone: { label: "手机号", type: "text", }, code: { label: "验证码", type: "text" }, }, async authorize(credentials) { const params = { phone: credentials?.phone ?? "", code: credentials?.code ?? "", }; const env = process.env.H5_OPERATION_ENV || process.env.NODE_ENV; let host; switch (env) { case "DEV": host = "xxx"; break; case "qa": host = "xxx"; break; case "prod": host = "xxx; break; default: break; } const res = await request.get( xxx, { params } ); const user = await res.payLoad; if (res.status === "SUCCESS" && user) { return user; } else { throw new Error(res.error); } }, }), ], pages: { signIn: "/Login/", }, callbacks: { async jwt({ token, user }) { if (user) { token.accessToken = (user as any)?.accessToken; token.name = (user as any)?.loginUserName as string; } return token; }, async session({ session, token }) { (session as Session & { accessToken: string | undefined }).accessToken = token.accessToken as string; if (session.user) { session.user.name = token.name as string; } return session; }, signIn({ user }) { request.interceptors.request.use((url, opts) => { let headers: { Authorization?: string } = {}; if ((user as any)?.accessToken) { headers.Authorization = `API-Bearer ${(user as any).accessToken}`; } return { url, options: { ...opts, ...headers }, }; }); return true; }, }, secret: process.env.NEXTAUTH_SECRET, debug: true, }); 
    // .env.development H5_OPERATION_ENV = DEV NEXTAUTH_URL_INTERNAL = http://localhost:3000/ NEXTAUTH_URL = http://localhost:3000/ NEXTAUTH_SECRET = xxx 
    // login.tsx const login = async (values: any) => { const res = await signIn('credentials', { ...values, redirect: false }) if (res?.ok) { const session = await getSession() getUserAuth({ currentUser: session?.user?.name ?? '' }).then(res => { if (res?.status === 'SUCCESS') { dispatch({ type: 'setState', payload: { powerList: res?.payLoad?.powerList?.map((power: any) => power?.powerCode) } }) } }) router.push('/home') } 
    //home.tsx export const getServerSideProps: GetServerSideProps<IndexProps> = async cOntext=> { const session = await getSession(context); console.log(session, 'first getServerSideProps'); // 第一次进入返回了 null let data: never[] = [] if ((session as any)?.accessToken) { console.log(session, 'getServerSidePropsGetSession'); const res = await fetch(`http://xxx`, { headers: { Authorization: `API-Bearer ${(session as any).accessToken}` } }) await res?.json().then(respOnse=> { console.log(data, 'json()'); if (response.status === 'SUCCESS') { data = response.payLoad.list } }) } return { props: { list: JSON.stringify(data) ?? [] } } } export default function Home(props: IndexProps) { const { data: session } = useSession() // 这里是 ok 的 } 
    // package.json "next": "12.2.3", "next-auth": "^4.10.3", 
    2 条回复    2023-01-19 17:11:21 +08:00
    violetlai
        1
    violetlai  
       2023-01-19 15:31:53 +08:00
    感觉你的登录流程有点奇怪,主要需求是 token 持久化?

    最近我也在做 ssr 只不过使用了 Nuxt3 ,登录流程是客户端发请求=》服务端处理返回结果 token=》保存 session=》 redis?=》 set-cookie=》拿 cookie
    可以参考下
    philsky28
        2
    philsky28  
    OP
       2023-01-19 17:11:21 +08:00
    @violetlai 是为了 token 持久化,以前直接放在了 localStorage 里,但是用 SSR 时,getserversideprops 方法中实际环境是服务端,没法拿到浏览器环境的 token ,所以现在改用 session 存储
    关于     帮助文档     自助推广系统     博客     API     FAQ     Solana     5238 人在线   最高记录 6679       Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 26ms UTC 05:51 PVG 13:51 LAX 22:51 JFK 01:51
    Do have faith in what you're doing.
    ubao snddm index pchome yahoo rakuten mypaper meadowduck bidyahoo youbao zxmzxm asda bnvcg cvbfg dfscv mmhjk xxddc yybgb zznbn ccubao uaitu acv GXCV ET GDG YH FG BCVB FJFH CBRE CBC GDG ET54 WRWR RWER WREW WRWER RWER SDG EW SF DSFSF fbbs ubao fhd dfg ewr dg df ewwr ewwr et ruyut utut dfg fgd gdfgt etg dfgt dfgd ert4 gd fgg wr 235 wer3 we vsdf sdf gdf ert xcv sdf rwer hfd dfg cvb rwf afb dfh jgh bmn lgh rty gfds cxv xcv xcs vdas fdf fgd cv sdf tert sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf shasha9178 shasha9178 shasha9178 shasha9178 shasha9178 liflif2 liflif2 liflif2 liflif2 liflif2 liblib3 liblib3 liblib3 liblib3 liblib3 zhazha444 zhazha444 zhazha444 zhazha444 zhazha444 dende5 dende denden denden2 denden21 fenfen9 fenf619 fen619 fenfe9 fe619 sdf sdf sdf sdf sdf zhazh90 zhazh0 zhaa50 zha90 zh590 zho zhoz zhozh zhozho zhozho2 lislis lls95 lili95 lils5 liss9 sdf0ty987 sdft876 sdft9876 sdf09876 sd0t9876 sdf0ty98 sdf0976 sdf0ty986 sdf0ty96 sdf0t76 sdf0876 df0ty98 sf0t876 sd0ty76 sdy76 sdf76 sdf0t76 sdf0ty9 sdf0ty98 sdf0ty987 sdf0ty98 sdf6676 sdf876 sd876 sd876 sdf6 sdf6 sdf9876 sdf0t sdf06 sdf0ty9776 sdf0ty9776 sdf0ty76 sdf8876 sdf0t sd6 sdf06 s688876 sd688 sdf86