Reputation: 128
I am using AWS Cognito as authentication provider for my Next.js (version 13) app, with the help of Next-Auth. When I try to login, it is getting successful, I am able to get the session using useSession() hook in the components.
But I do have a REST API secured with same AWS Cognito configuration. The idea here is to get the user Bearer token from the UI and pass it to the REST API, and get user specific info. Currently I am unable to get the JWT token, which I will be using to authenticate the REST API.
app>api>auth>[...nextauth]>route.js
import NextAuth from "next-auth";
import CognitoProvider from "next-auth/providers/cognito";
export const authOptions = {
providers: [
CognitoProvider({
clientId: process.env.COGNITO_CLIENT_ID,
clientSecret: process.env.COGNITO_CLIENT_SECRET,
issuer: process.env.COGNITO_ISSUER,
authorization: {
params: {
scope: "openid",
},
},
}),
],
session: {
jwt: true
},
secret: process.env.NEXTAUTH_SECRET,
jwt: {
encryption: true,
},
callbacks: {
async jwt({ token, user }) {
return { ...token, ...user };
},
async session({ session, token, user }) {
session.user = token;
return session;
},
},
};
const handler = NextAuth(authOptions);
export { handler as GET, handler as POST };
When I use the useSession to print it to the console, I don't have information about the JWT token
Upvotes: 3
Views: 1633
Reputation: 131
I had this issue recently and the cause is the cognito user confirmation status is "Force change password". With this in mind, it will return only the session token.
Try changing the password to make UI for changing it or enable their hosted UI for a faster workaround.
and on JTW callbacks make sure to add:
if (user || account){
console.log(user,account,token)
}
since it's an async callback and check if your tokens exist.
Upvotes: 1
Reputation: 16219
You might need to check the account
object that the jwt
callback provides, you can find additional information, usually if the provider you use is returning a token, it will be found there:
async jwt({ token, user, account }) {
return {...token, ...user, ...account};
},
Also you have to add
idToken: true,
to the provider object
Upvotes: 1