Store JWT for Server Sessions
Unanswered
Northeast Congo Lion posted this in #help-forum
Northeast Congo LionOP
Hello, I am trying to set up my src/app/api/auth/[...nextauth]/route.ts file such that when I call getServerSession, I can access the JWT that I am storing in the user object. I can see that the user object does have the JWT as expected when I log it on the JWT callback and in the authorize function. The issue is that the response to await getServerSession() calls does not end up having the token. Now I did extend the User interface to include this token field, and same with the Session interface.
What am I missing here? Is there a better way to do this? I just want to be able to authorise through my custom API.
What am I missing here? Is there a better way to do this? I just want to be able to authorise through my custom API.
import { authoriseUser } from "@/oauth";
import { randomBytes, randomUUID } from "crypto";
import NextAuth from "next-auth/next";
import Credentials from "next-auth/providers/credentials";
const handler = NextAuth({
providers: [
Credentials({
name: 'Credentials',
credentials: {
username: { label: 'Username', type: 'text', placeholder: 'username' },
password: { label: 'Password', type: 'password' }
},
async authorize(credentials) {
if (!credentials?.username || !credentials.password) {
return null
}
const user = await authoriseUser(credentials.username, credentials.password)
return user
},
}),
],
session: {
strategy: 'jwt',
generateSessionToken() {
return randomUUID?.() ?? randomBytes(32).toString('hex')
},
},
callbacks: {
async jwt(params) {
params.token.accessToken = params.user.token
return params.token
},
async session(params) {
params.session.token.accessToken = params.token.accessToken
return params.session
},
},
})
export { handler as GET, handler as POST }