TLTR: Looking to improve authentication flow with NextAuth and FirebaseAuth when having a 3rd Party API call that fetches workspace and revalidates Bearer Token (using firebase-admin) upon call.
Hey, I encountered an issue while fetching content from a Laravel API.
I am using the Next.js App Router with NextAuth and FirebaseAuth.
The flow goes like this: I pass login details to signInWithEmailAndPassword, then I use signIn('credentials') to pass the tokenId. During the signIn flow, I send a POST request to get the workspace info, ensuring a user is linked to a workspace.
CredentialProvider (nextAuth)
authorize: async ({ idToken }: any, _req) => {
if (idToken) {
try {
const decoded = await firebaseAdmin.auth().verifyIdToken(idToken);
const scheme = await getSchemeOnLogin(idToken);
return { ...decoded }
} catch (err) {
console.error(err);
}
}
return null;
}
getWorkspaceInfo
return new Promise(async (resolve, reject) => {
try {
await new Promise(resolve => setTimeout(resolve, 3000));
await fetch('http://localhost:8000/api/v1/workspace', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: Bearer ${token},
},
})
.then(async (res) => {
if (!res.ok) {
reject('Error Occurred while fetching user data');
}
const responseData = await res.json(); // Save to local storage
console.log(responseData);
resolve(responseData);
});
} catch (err) {
reject(err);
}
});
On the backend, I revalidate the token I receive using firebase-admin, after which I either send a 200 status or a 401.
public function login(Request $request) {
if (!$this->isTokenValid($request)) {
return $this->getJsonResponse("error", "User not Logged In",sonResponse::HTTP_UNAUTHORIZED);
}
return $this->getJsonResponse("success", "Successfully Obtained Workspace Details", JsonResponse::HTTP_OK, $infoString); }
The issue arises when I send the request to Laravel. It keeps returning a 401 status. What helped was implementing a timeout of 3 seconds, which is rather hacky.
Thanks!