Reputation: 948
I have express app, running on port 8000, I also have react on port 3000. I am trying to implement google oauth.
This is what I did.
I try to send get request to my api endpoint, then my express server redirect user to google Sign in.
And then, how can I send token from server to client from get
request?
Here's my express code.
I try to send cookies directly from the server,
but I don't know why the cookies is not available on port 3000 which is my react app.
Is there any neat way to send jwt to client?
router.get(
"/google/callback",
passport.authenticate("google", {
scope: ["profile", "email"],
failureRedirect: "/login",
session: false,
}),
(req, res) => {
const payload = {
id: req.user.id,
};
jwt.sign(payload, secret, { expiresIn: tokenLife }, (err, token) => {
if(err) {
console.log('error', err)
}
const jwt = `Bearer ${token}`;
console.log('ini token', token)
const htmlWithEmbeddedJWT = `
<html>
<script>
// Save JWT to cookie
// document.cookie = 'token=${jwt};'
document.cookie = 'token=${jwt}; SameSite=None; Secure'
// Redirect browser to root of application
window.open('http://localhost:3000/login', '_self')
</script>
</html>
`;
res.send(htmlWithEmbeddedJWT);
});
}
);
Upvotes: 0
Views: 361
Reputation: 2465
It is not available because you have responded to the google call and then redirected the page on a client to the localhost apparently cookies will not be available.
The common way to handle auth in such cases is to define a success redirect that will expect to receive somekind of a token in query params.
Upvotes: 1