Next js getServerSideProps, 404 error not found - javascript

I am taking my time trying to understand "fetching data" in next js, i am trying to directly access a url that has a unique token and i keep getting 404 not found
export async function getServerSideProps({params}){
try{
let res = await fetch(`${HOST}reset/${params.token}/`)
let token = await res.json()
return {
props:{token}
}
}
catch(err){
return {
props:[]
}
}
}
any idea why?
the token is set in the backend, and it get discarded after it has been used (in this case the user pressed submit to reset their password)
and i am not sure how i can locate token in getServerSideProps?

Related

AadTokenProvider returns access token from old user

We are developing Microsoft Sharepoint "Widgets" using javascript(React) and aadTokenProviderFactory to acquire tokens.
import { WebPartContext } from "#microsoft/sp-webpart-base";
const getMSToken = async (context: WebPartContext) => {
const provider = await context.aadTokenProviderFactory.getTokenProvider();
const token = await provider.getToken('https://graph.microsoft.com');
return token;
}
This token is valid and everything works fine. But when switching users I receive a token from the old user.
How to solve this issue and acquire tokens for the user that is currently signed in?
Issue solved.
getToken method has 2nd parameter called useCachedToken: boolean.
const token = await provider.getToken('https://graph.microsoft.com', false);

In Next.js getServerSideProps, how can I fetch cookie from browser to identify the user

I am developing an e-commerce site. A user has selected the items. To view his cart and checkout he clicks on the cart icon in NavBar which navigates him to myCart.js page. I am using getServerSideProps to get JWT from the browser, decode it and verify the user. Code is as below:
let jwtoken;
export async function getServerSideProps(req, res) {
if (
req.headers.authorization &&
req.headers.authorization.startsWith('Bearer')
) {
jwtoken = req.headers.authorization.split(' ')[1];
} else if (req.cookies.jwt) {
jwtoken = req.cookies.jwt;
}
if (!jwtoken) {
return res.status(423).redirect('/emptyCart');
const decoded = await promisify(jwt.verify)(jwtoken, process.env.JWT_SECRET);
currentUser = await User.findById(decoded.id);
if (!currentUser)
return res.status(401).redirect('/signup');
Note: cookie is httpOnly.
I get a runtime error: 'headers not defined'
Now if I remove the code containing req.headers and use only eq.cookies.jwt > gives me another error cookies not defined.
I worked on this issue for four days and tried so many solutions offered in Stackoverflow and also from other developer portals like flavio, reddit and others.
The getServerSideProps function expects a single context parameter, which contains the req/res objects you're trying to access.
Change your getServerSideProps function to have the following signature:
export async function getServerSideProps({ req, res }) {
console.log(req.cookies); // Logs all cookies from the request
}

FirebaseAuthError when using Nookies to get token. (NextJS)

I'm trying to verify if the user was able to complete the registration successfully. For this, I want to get the user's token via cookies, as in the following code:
[...]
export async function getServerSideProps(ctx) {
try {
const cookies = nookies.get(ctx)
console.log(JSON.stringify(cookies, null, 2));
const token = await firebaseAdmin.auth().verifyIdToken(cookies.token)
const { email } = token
return {
props: { message: `${email} was successfully registered!`}
}
} catch (err) {
console.log(err)
return { props: { message: 'Error'} }
}
}
[...]
This function returns the following error:
errorInfo: {
code: 'auth/argument-error',
message: 'Decoding Firebase ID token failed. Make sure you passed the entire string JWT which represents an ID token. See
https://firebase.google.com/docs/auth/admin/verify-id-tokens for
details on how to retrieve an ID token.' }
I believe I must be misusing nookies.get(ctx), and I say this because the retrieved cookie (token) is equal to a "", which doesn't make much sense to me. Then, how can I properly use nookies to get that token?
I would appreciate it, if anyone could help me to find out what I'm missing out.
Thanks in advance.
EDIT: The user account is created, and the email and password are stored in the Firebase Auth. It is only this piece of code that does not work.
Since Next 10.0.4 you can get cookies without nookies
const cookies = ctx.req.cookies
try in this way, if you still getting token as empty check the way that you set cookies.

Firebase ID Token expiration in an hour

so I am using redux-saga in my react-native app and tried to use refresh token but didn't work, so my approach was the following in app.js in order to get the token specifically for each request and force refresh it:
handleResponse = async () => {
const {dispatch} = this.store;
await axios.interceptors.request.use(config => {
// Important: request interceptors **must** return the request.
console.log("refreshToken")
let user = firebase.auth().currentUser;
firebase.auth().onAuthStateChanged(function(user) { if (user) {
console.log("auth changed: ",user)
user.getIdToken(true).then((token) => {
setAccessToken(token);
config.headers.authorization = token;
}
);
} else { console.log("didn't auth change") } });
console.log("req in handle response: ",JSON.stringify(config));
return config;
});
axios.interceptors.response.use(config => config, (err) => {
if (err.response) {
const response = err.response;
const state = this.store.getState();
if (
response.status === 401
&& state.auth.isAuthenticated
) {
dispatch(logout());
}
}
return Promise.reject(err);
});
};
But it always ends up after an hour throwing me the following error::
Firebase ID token has expired. Get a fresh token from your client app and try again (auth/id-token-expired). See https://firebase.google.com/docs/auth/admin/verify-id-tokens for details on how to retrieve an ID token.
so I was wondering if there's another approach I can try to solve the issue from my side?
Thanks in advance.
Firebase auth tokens automatically refresh every hour. That's a function of the SDK, and you don't have to do anything to enable it.
You definitely do not want to call firebase.auth().onAuthStateChanged for each request. That starts a persistent listener, and adds a new callback every time it's used. Typically you add just one listener globally for your app, and use its updates as they happen.
If you need to know when the SDK refreshes the token in order to get a new one immediately, you should instead use onIdTokenChanged to set up a callback that will be invoked every time the user's token changes. Again, you should only set up one of these globally for your app, and use its current value at the time of the request.

jwt.decode() stuck instead of returning an error on malformed token

On an express nodejs server I try to validate a token with the jsonwebtoken package (v8.5.1). I experience something really odd and don't seem to find a solution for this.
Whenever I try to verify a malformed token the jwt.verify method becomes stuck instead of throwing the usual error which I expected. Can someone please point out what I am doing wrong. Underneath you'll find the code which becomes completely stuck.
When the token is valid, the console.log statement returns the content of the jwt. When it is invalid, the console.log statement is never run and the endpoint just never responds. So for some reason, it becomes completely stuck on the jwt.verify method.
router.post('/session', async (req, res) => {
try {
const token = req.headers['x-auth-token'];
if (!token) {
return res.json(false);
}
const verified = jwt.verify(token, process.env.JWT_SECRET);
console.log(verified);
if (!verified) {
return res.json(false);
}
return res.json(true);
} catch (e) {
return res.status(500);
}
});
Hey in that case I would suggest to use promisify and wait for the promise to throw an error.
const verified = await promisify(jwt.verify)(req.params.token, process.env.JWT_SECRET);
using this require statement:
const { promisify } = require('util');
you can check the node.js documentation
I still don't know exactly why it behaved the way it did, but at least I found a workaround that answers immediately when the token is incorrect instead of returning nothing.
I added a callback to the jwt.verify function:
const verified = jwt.verify(
token,
process.env.JWT_SECRET,
(err, verified) => {
if (err) {
return res.status(401).json('Error');
}
return verified;
}
);

Categories

Resources