nuxt-auth 无法使用刷新提供程序获取令牌数据

问题描述 投票:0回答:1

我在 Nuxt 3 中的登录功能方面遇到一些问题。

我已经安装了一个包@sidebase/nuxt-auth用于用户身份验证。 这些是我在文件 nuxt.config.ts

中的配置
auth: {
    globalAppMiddleware: true,
    baseURL: backendUrl,
    provider: {
      type: "refresh",
      endpoints: {
        signIn: { path: "/login/", method: "post" },
        signOut: { path: "/logout/", method: "get" },
        signUp: { path: "/register/", method: "post" },
        refresh: { path: "/refresh/", method: "post" },
        getSession: false,
      },
      pages: {
        login: "/login",
        register: "/register",
      },
      token: {
        signInResponseTokenPointer: "/access",
      },
      refreshToken: { signInResponseRefreshTokenPointer: "/refresh" },
    },

    enableSessionRefreshPeriodically: 5000,
    enableSessionRefreshOnWindowFocus: true,
    globalMiddlewareOptions: {
      allow404WithoutAuth: true, // Defines if the 404 page will be accessible while unauthenticated
      addDefaultCallbackUrl: "/", // Where authenticated user will be redirected to by default
    },
  },

这是在文件中获取我的令牌的代码:server/api/auth/token.get.ts

import { getToken } from "#auth";
export default eventHandler(async (event) => {
  const token = await getToken({ event, cookieName: "auth" });
  console.log(token);
  return token || "no token present";
});

打印token的页面代码:

<script setup lang="ts">
definePageMeta({
    auth : false,
})
const headers = useRequestHeaders(['cookie'])
const {data : token} = await useFetch('/api/auth/token', {headers});
</script>
<template>
    <pre>
        {{ token }}
    </pre>
</template>

我的用户登录逻辑:

definePageMeta({
  layout: "front",
  auth: {
    unauthenticatedOnly: true,
    navigateAuthenticatedTo: '/token',
  }
});

const loginWithCredentials = async () => {
    try {
      let res = await signIn(
        { ...formData },
        { callbackUrl: '/token' } // Where the user will be redirected after a successiful login
      )
      console.log(res);
    } catch (error) {
      console.log("error", error);
    } 
}

我必须提到,我正在使用自定义后端来返回带有 JWT 令牌属性“访问”和“刷新”的 JSON 数据。

因此,如果我使用正确的用户凭据向 url backEndUrl/login/ 发送发布请求,我会得到如下响应:

JsonResponse

我尝试将访问令牌放入https://jwt.io/,这得到了这个结果:

JWTResponse

我期待 getToken() 返回有效负载数据,但它返回 null

可能是什么问题?

javascript jwt nuxt3 nuxt-auth
1个回答
0
投票

请勿在

server/api/auth/
中定义新路由,因为它是
@sidebase/nuxt-auth
端点的默认基本路径。 (参考

尝试使用

server/api/token.get.ts

© www.soinside.com 2019 - 2024. All rights reserved.