I have this base options object:
const options = {
secret: process.env.NEXTAUTH_SECRET,
site: process.env.NEXTAUTH_URL,
session: {
strategy: "jwt",
maxAge: 7 * 24 * 60 * 60 // the session will last 7 days
},
providers: [
CredentialsProvider({
name: "Credentials",
async authorize(credentials, req) {
const context = getContext(req);
const [ token, user, error ] = await userApi.authenticateByCredentials(credentials?.username, credentials?.password, context);
return !error && user?.id ? {
id: user.id,
name: `${user.firstName} ${user.lastName}`,
email: user.email,
image: null, // TODO: user.avatar
accessToken: token
} : null;
}
}),
],
callbacks: {
// Getting the JWT token from API response
async jwt({ token, user /*, account, profile, isNewUser*/ }) {
if (user) {
token.accessToken = user.accessToken;
}
return token
},
async session({ session, token, user }) {
session.accessToken = token.accessToken;
return session;
},
}
};
All works fine. The components can retrieve this access token with:
export default function SomeComponent() {
const { data:session, status } = useSession()
const user = session?.user;
const accessToken = session?.accessToken;
console.log("Access token:", accessToken);
return ...;
}
The accessToken may become invalid for various reasons since it is obtained from a third-party application, so how do I automatically invalidate NextAuth session if the accessToken becomes invalid?
I am assuming changing the jwt callback like this:
callbacks: {
// Getting the JWT token from API response
async jwt({ token, user /*, account, profile, isNewUser*/ }) {
if (user) {
token.accessToken = user.accessToken;
// validate access token
} else {
if (!isValidAccessToken(token.accessToken)) {
return null;
}
}
return token
},
...
},
This does not look alright to me. What's the correct way to validate this accessToken and invalidate the session otherwise?