How do I customize my session to include the sub from an OIDC provider?
Unanswered
Saltwater Crocodile posted this in #help-forum
Saltwater CrocodileOP
Here is my code:
I want the sub field to be available in my session. I'm currently getting the session using:
import NextAuth from "next-auth"
import TwitchProvider from "next-auth/providers/twitch"
export const authOptions = {
providers: [
TwitchProvider({
clientId: process.env.TWITCH_CLIENT_ID || '',
clientSecret: process.env.TWITCH_CLIENT_SECRET || '',
authorization: { params: { scope: "openid user:read:email" }},
profile(profile) {
return {
id: profile.sub,
name: profile.preferred_username,
email: profile.email,
image: profile.picture,
}
}
}),
// ... you can add more providers here
],
secret: process.env.AUTH_SECRET,
}
const handler = NextAuth(authOptions)
export {handler as GET, handler as POST}I want the sub field to be available in my session. I'm currently getting the session using:
let session = await getServerSession(authOptions);2 Replies
Saltwater CrocodileOP
I was trying to use the session callback to do this and was failing...but I finally got it working:
import NextAuth, { Account, Profile, Session, User } from "next-auth";
import { JWT } from "next-auth/jwt";
import TwitchProvider from "next-auth/providers/twitch";
interface CustomSession extends Session {
user: {
id?: string;
name?: string;
email?: string;
image?: string;
};
}
export const authOptions = {
providers: [
TwitchProvider({
clientId: process.env.TWITCH_CLIENT_ID || '',
clientSecret: process.env.TWITCH_CLIENT_SECRET || '',
authorization: { params: { scope: "openid user:read:email" }},
profile(profile) {
return {
id: profile.sub,
name: profile.preferred_username,
email: profile.email,
image: profile.picture,
}
}
}),
// ... you can add more providers here
],
callbacks: {
async session({ session, token }: { session: Session, token: JWT }): Promise<Session> {
console.log('In Session Callback: ', session, token);
const customSession = session as CustomSession;
// Ensure custom fields in token are available and correctly typed
if (token && session) {
customSession.user.id = token.sub;
console.log('Custom Session: ', customSession);
}
return customSession;
}
},
secret: process.env.AUTH_SECRET,
}
const handler = NextAuth(authOptions)
export {handler as GET, handler as POST}Adding the custom session callback did what I need.