nextauthjs / next-auth

Authentication for the Web.
https://authjs.dev
ISC License
24.63k stars 3.46k forks source link

How to get hold of access_token or id_token when using SvelteKitAuth with Cognito? #8156

Closed bluprince13 closed 1 year ago

bluprince13 commented 1 year ago

Question šŸ’¬

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 https://stackoverflow.com/questions/69068495/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.

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.

Also asked on StackOverflow: https://stackoverflow.com/questions/76741555/how-to-get-hold-of-access-token-or-id-token-when-using-sveltekitauth-with-cognit

How to reproduce ā˜•ļø

// 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;

Contributing šŸ™ŒšŸ½

Yes, I am willing to help answer this question in a PR

bluprince13 commented 1 year ago

I think it was just a typo in the end. token.accessToken should have been token.access_token. I could swear there was something other issue, but when I corrected the typo and tried a few days later, everything seemed fine.

connercms commented 12 months ago

Can you reveal how you made the code in your callbacks configuration TypeScript compliant? I am using the same code. It is working fine. But my files are throwing errors everywhere I reference this now because these properties don't exist on the session or token types defined in the package

image

niklastreml commented 12 months ago

You probably need to augment the session type. Take a look at this issue and the documentation for module augmentation here.

bluprince13 commented 12 months ago

Type augmentation in my code: https://github.com/bluprince13/notesapp/blob/main/src/types/auth.d.ts

connercms commented 11 months ago

Thank you both very much. Never augmented types from a package before. Worked perfectly