I have a project and I made the backend using nodejs. I made a user registration module and the authentication generates a token! This token will need to be used in other requests where the user must be logged in.
What is the best way to store this token on the frontend using cakephp 4?
Is there any component? Is it safe to store this token using the session?
I would appreciate it if someone could help analyze this case.
This is my authentication method:
public function login()
{
$http = new Client();
if ($this->request->is('post')) {
$response = $http->post(
'http://localhost:8889/api/auth/login',
[
'email' => $this->request->getData("username"),
'password' => $this->request->getData("password"),
]
);
if ($response->getStatusCode() == 401) {
return $this->redirect($this->referer());
}
if ($response->isOk()) {
$json = $response->getJSON();
return $this->redirect(['action' => 'home', 'controller' => 'Pages']);
}
}
}
Return 200 contains an accessToken.
The best way to store the token is with an HttpOnly Cookie.
According to the Microsoft Developer Network, HttpOnly is an additional flag included in a Set-Cookie HTTP response header. Using the HttpOnly flag when generating a cookie helps mitigate the risk of client-side script accessing the protected cookie (if the browser supports it).
If you store it in a LocalStorage/SessionStorage then it can be easily grabbed by an XSS attack (from Javascript/Client side)
The CakePHP 4 way to do it is like this:
https://book.cakephp.org/4/en/controllers/request-response.html#creating-cookies
$cookie = new Cookie(
'jwt_token', // name
'token', // value
new DateTime('+1 hour'), // expiration time
'/', // path
'example.com', // domain
true, // secure only?
true // http only -> this is what you need
);