sidebase / nuxt-auth

Authentication built for Nuxt 3! Easily add authentication via OAuth providers, credentials or Email Magic URLs!
https://auth.sidebase.io
MIT License
1.25k stars 162 forks source link

Token and Session null when called from cachedEventHandler #845

Closed flim closed 1 month ago

flim commented 1 month ago

Environment

Reproduction

When authenticated. Call internal server api (eg. /api/test) from page with

// /pages/home.vue
<script setup lang="ts">
// [...]
const { data, status } = await useFetch('/api/test')
// [...]
</script>

On server side

// /server/api/test.ts
import {getToken} from "#auth";

export default cachedEventHandler(async (event) => {
    const token = await getToken({event})

    console.log(token) // null
}, {
    swr: true,
    maxAge: 60
});
// /server/api/test2.ts
import {getToken} from "#auth";

export default eventHandler(async (event) => {
    const token = await getToken({event})

    console.log(token) // not null
});

Describe the bug

As an authenticated user, when I call the internal server api that implementing cachedEventHandler, the value returned by getToken and getServerSession are null.

But works when using classical eventHandler.

Additional context

No response

Logs

No response

phoenix-ru commented 1 month ago

@flim I believe you are doing something conceptually wrong - why would you want to cache authenticated requests? This is a security vulnerability. h3 is correctly protecting you from shooting your own legs.

[!CAUTION] I highly advise you against caching any user-specific data - it IS a vulnerability regardless of your usecase.

In case you still want to cache this - you need to provide header names (authorization and cookie) to varies: https://nitro.unjs.io/guide/cache#options