Cookie Authentication
Closed this issue · 5 comments
current behavior: storage auth gets the auth token from header, and sends it via response json
expected behavior: get and set tokens from cookie
step 1:
app.get('/jwt', (req, res) => {
const token = jsonwebtoken.sign({ user: 'johndoe' }, jwtSecret);
res.cookie('token', token, { httpOnly: true });
res.json({ token });
});
note: update the proxy
field in your create-react-app later to avoid CORS errors
if doesn't work:
To allow receiving & sending cookies by a CORS request successfully, do the following.
Back-end (server): Set the HTTP header Access-Control-Allow-Credentials value to true. Also, make sure the HTTP headers Access-Control-Allow-Origin and Access-Control-Allow-Headers are set and not with a wildcard *.
For more info on setting CORS in express js read the docs here
Front-end (client):
ES6 fetch() credentials: 'include'
A future release of Chrome will only deliver cookies with cross-site requests if they are set with SameSite=None and Secure.
Or
Avoid having to use CORS in combination with cookies. You can achieve this with a proxy.
If you for whatever reason don't avoid it. The solution is above.
It turned out that Chrome won't set the cookie if the domain contains a port. Setting it for localhost (without port) is not a problem. Many thanks to Erwin for this tip!
step 2:
$ npm install cookie-parser
app.use(cookieParser());
the token will now be on req.cookies.token
add CSRF protection:
$ npm install csurf
const csrfProtection = csrf({
cookie: true
});
app.use(csrfProtection);
app.get('/csrf-token', (req, res) => {
res.json({ csrfToken: req.csrfToken() });
});
then add this as header to any request made by the client