I've built an authorization server with Express.js that works when testing with Postman where it saves the access and rotating refresh token as signed cookies.
However, what I completely forgot, was that my backend and frontend are two completely separate servers and domains. I tried enabling the Access-Control-Allow-Credentials, but that didn't work. I don't get any error messages, the cookies simply aren't being saved.
Here is my login controller from the backend:
const userLogin = async (req, res, next) => {
const { email, password } = req.body;
if (!email || !password) return res.sendStatus(400);
try {
const login = await loginUser(email, password);
if (login == 'wrong_email_or_password') return res.status(200).json({ error: login });
res.header('Access-Control-Allow-Credentials', true);
res.cookie('access', login.accessToken, { httpOnly: true, secure: (env != 'dev'), signed: true });
res.cookie('refresh', login.refreshToken, { httpOnly: true, secure: (env != 'dev'), signed: true });
res.status(200).json(login);
} catch(e) {
console.log(e.message);
res.sendStatus(500) && next();
}
}
And after I encountered some CORS issues, I also did app.use(cors({ origin: true, credentials: true }));, which resolved the issue. For production I'll probably also add a CORS-whitelist.
And here's my Nuxt.js method that will be called upon submitting the register-form:
async register () {
try {
if (!(this.firstname && this.lastname && this.username && this.email && this.password)) throw new Error('Pflichtfelder ausfüllen')
const res = await axios.post(`${this.$axios.defaults.baseURL}register`, {
firstname: this.firstname,
lastname: this.lastname,
username: this.username,
email: this.email,
password: this.password
}, {
withCredentials: true,
credentials: 'include'
})
console.log(res)
this.$router.go()
} catch (e) {
this.error = e.message
console.error(e)
}
}
I wish I could provide some more helpful information other than "doesn't work, help pls", but as I said, I don't get any errors whatsoever, so I really don't even know where to look. :(
Alright, it would seem that what I'm trying to do is impossible. Cookies coming from third-party domains are not allowed, which makes sense now that I think of it...
For anyone interested, my solution is to just save both tokens in localStorage. Since I am using rotating refresh tokens this isn't that big of a deal.