My node.JS passport authentification check is stuck in an infinite loop if I return 400 status for requests which are not authentified:
//ensure authentification
function authorizeApi(req, res, next) {
if (req.isAuthenticated()) {
return next();
}
else res.status(400).json({
message : "User Not Authenticated",
user : null
})
}
// retrieve logged in user profile
router.post("/login/success",authorizeApi, (req, res) => {
...
res.json({
success: true,
message: "user has successfully been authenticated",
user: req.user,
cookies: req.cookies
});
}
app.use(bodyParser.json({ limit: "50mb", extended: true }));
app.use(bodyParser.urlencoded({ extended: true }));
app.use("/auth", authRoutes);
If I return only the profile for users which are authentificated I get a request from the client which remains in pending...
EDIT: After user is logged in loop ends and back-end returns the user profile info.
My client application is build in React. The function that gets the user profile is a fetch inside:
login();
}, [])
// gets login details
function login() {
fetch(config.baseURL + config.baseLOCATION + "/auth/login/success/", {
method: "POST",
credentials: "include",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
"Access-Control-Allow-Credentials": true,
}
})
.then(response => {
if (response.status === 200) return response.json();
throw new Error("failed to authenticate user");
})
.then(responseJson => {
sessionStorage.setItem('exp', responseJson.user.exp);
....
dispatch({
type: UPDATE_PROFILE,
payload: {
role: responseJson.user.roles,
....
}
});
}
)
.catch(error => {
setState({
authenticated: false,
error: "Failed to authenticate user"
});
console.log(error);
_handleLogoutClick();
});
}
UPDATE: The issue is being generated from the frontend client.
I have updated the client request:
.then(response => {
if (response.status) return response.json();
})
.then(responseJson => {
if(responseJson.success === true) {
...
}
else {
...
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.