We have our own OAuth 2.0 implementation and I am using next-auth to connect and get a jwt in my Next.js app.
Output:
At the moment, I am able to login. However, I get null as token on the client-side.
Steps I have implemented:
- Added the
next-authProvider component at the top-level.
function MyApp({ Component, pageProps }) {
return (
<Provider
options={{
clientMaxAge: 0,
keepAlive: 0,
}}
session={pageProps.session}>
<Component {...pageProps} />
</Provider>
);
}
- The file:
pages/api/auth/[...nextauth].js:
export default NextAuth({
providers: [
{
id: "quot-test",
name: "quot-test",
type: "oauth",
version: "2.0",
scope: "openid email",
state: true,
protection: "state",
params: { grant_type: "authorization_code" },
idToken: true,
authorizationUrl:
"http://localhost:9000/oauth2/authorize?response_type=code",
accessTokenUrl: "http://localhost:9000/oauth2/token",
requestTokenUrl: "http://localhost:9000/oauth2/jwks",
clientId: process.env.QUOT_ID,
clientSecret: process.env.QUOT_SECRET,
},
],
secret: process.env.SECRET,
debug: true,
session: {
jwt: true,
maxAge: 60 * 5,
},
jwt: {
secret: process.env.SECRET,
encryption: false,
},
callbacks: {
async signin(user, account, profile) {
console.log("user", user, account, profile);
return true;
},
async jwt(token, user, account, profile, isNewUser) {
console.log(token);
console.log(user);
console.log(account);
console.log(profile);
console.log(isNewUser);
if (account.accessToken) {
token.accessToken = account.accessToken;
}
return Promise.resolve(token);
},
async session(session, token) {
console.log(session);
console.log(token);
return session;
},
},
});
This is where the first issue is: none of the callbacks are triggered and no console.log is printed on the terminal. There appears to be something wrong in my config above?
- Added
signIn/ signOutto sign-in with auth service on the Home page.
import { signIn, signOut, useSession, getSession } from "next-auth/client";
export default function Home(){
...
const [session, loading] = useSession();
console.log(session); // prints null after signin
return(
<button onClick={() =>signIn(null, { callbackUrl: "http://localhost:3000/happy" })}>
Sign
</button>
...
This is where the next issue is: even though the callbackUrl in signin function is to the page '/happy', I am still taken to home page!
- I have .env.local file in the root with the following:
NEXTAUTH_URL=http://localhost:3000/
QUOTECH_ID=quot-test
QUOTECH_SECRET=[secret-from-authenticator-goes-here]
SECRET=[random-string-goes-here]
What am I missing ? Why am I getting null once I am redirected by the client-app. It appears some of the options are being ignored in the [...nextauth].js file above?