Sing In Returns decoded token instead of encoded
Answered
Clytax posted this in #help-forum
ClytaxOP
Hey, I am trying to obtain the standard token when logging in, but currently, I am receiving the decoded version with 'exp' etc. How can I return the encoded version instead? Here is my authOptions file:"
import { connectDB } from "./mongodb";
import User from "@/models/user";
import type { NextAuthOptions } from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import bcrypt from "bcryptjs";
export const authOptions: NextAuthOptions = {
providers: [
CredentialsProvider({
name: "Credentials",
id: "credentials",
credentials: {
email: { label: "Email", type: "text", placeholder: "jsmith" },
password: { label: "Password", type: "password" },
},
async authorize(credentials) {
await connectDB();
const userFound = await User.findOne({
email: credentials?.email,
}).select("+password");
if (!userFound) throw new Error("Ungültige Email");
const passwordMatch = await bcrypt.compare(
credentials!.password,
userFound.password
);
if (!passwordMatch) throw new Error("Ungültiges Passwort");
return userFound;
},
}),
],
pages: {
signIn: "/login",
},
session: {
strategy: "jwt",
},
callbacks: {
async jwt({ token, user, session, trigger }) {
if (trigger === "update" && session?.name) {
token.name = session.name;
}
if (trigger === "update" && session?.email) {
token.email = session.email;
}
if (user) {
const u = user as unknown as any;
return {
...token,
id: u.id,
name: u.firstName,
email: u.email,
};
}
return token;
},
async session({ session, token }) {
return {
...session,
user: {
...session.user,
_id: token.id,
name: token.name,
email: token.email,
},
token,
};
},
},
};
Answered by Clytax
I made it work by adding a new token in the sessions part like this, incase someone needs it:
async session({ session, token }: any) {
let encodedToken = jwt.sign(
{ id: token.id, email: session?.user?.email },
process.env.JWT_SECRET,
{ expiresIn: "7d" }
);
return {
...session,
user: {
...session.user,
_id: token.id,
name: token.name,
email: token.email,
},
token: encodedToken,
};
},
2 Replies
ClytaxOP
Or do I have to encode the token again in the frontend? Would be nice to just get back the encoded token
ClytaxOP
I made it work by adding a new token in the sessions part like this, incase someone needs it:
async session({ session, token }: any) {
let encodedToken = jwt.sign(
{ id: token.id, email: session?.user?.email },
process.env.JWT_SECRET,
{ expiresIn: "7d" }
);
return {
...session,
user: {
...session.user,
_id: token.id,
name: token.name,
email: token.email,
},
token: encodedToken,
};
},
Answer