I am developing a SvelteKit app and am using Cognito as my authentication provider. For one of the AWS APIs I'm calling (IsAuthorizedWithToken), I need to provide the logged-in user's access/identity token. Essentially, I want to get hold of the tokens somehow in one of my +page.server.ts
file.
// somefolder/+page.server.ts
export async function load({ locals }) {
const session = await locals.getSession();
const { id_token, access_token } = session
// Make use of id_token, access_token
}
Inspired by how to get the provider access token in next-auth, I used the jwt
callback to get the tokens when the user logs in. I verfied the tokens were there in session
using console log.
However, as soon as I refresh the page the tokens become undefined
even though the user is still logged in and I have access to other properties in session like user.email
. By this I inferred that the token are only made available when the user logs in, not for subsequent requests.
// hooks.server.ts
import { SvelteKitAuth } from '@auth/sveltekit';
import Cognito from '@auth/core/providers/cognito';
import { AUTH_SECRET, COGNITO_USER_POOL_ID, COGNITO_CLIENT_SECRET } from '$env/static/private';
import { PUBLIC_COGNITO_CLIENT_ID } from '$env/static/public';
import type { Handle } from '@sveltejs/kit';
// https://authjs.dev/reference/sveltekit
export const handle = SvelteKitAuth({
secret: AUTH_SECRET,
providers: [
// https://authjs.dev/reference/core/providers_cognito
Cognito({
clientId: PUBLIC_COGNITO_CLIENT_ID,
clientSecret: COGNITO_CLIENT_SECRET,
issuer: `https://cognito-idp.us-east-1.amazonaws.com/${COGNITO_USER_POOL_ID}`
})
],
callbacks: {
async session({ session, token }) {
session.user && (session.user.sub = token.sub);
session.access_token = token.accessToken as string;
session.id_token = token.id_token as string;
console.log(session);
return session;
},
async jwt({ token, account }) {
if (account) {
token.access_token = account.access_token;
token.id_token = account.id_token;
}
return token;
}
}
}) satisfies Handle;
Q1: Why are the tokens only available when the users logs in, not for subsequent requests? What's SvelteKitAuth doing with the tokens?
Q2: What's the correct
way of getting hold of the tokens in my +page.server.ts
?
Whilst it'd be nice to get an answer to fix my current problem, I'm interested in understanding why things are this way.
GitHub issue also created: https://github.com/nextauthjs/next-auth/issues/8156