Hello, I am currently redoing a legacy web application that uses the PHP Parse SDK, and I am in the login authentication part. In the old application, we used $ _SESSION and ParseToken when doing
ParseUser::currentUser() to check if you have a session with a valid token, however the new application is being made using the REST architecture, where one of the REST concepts is that the server must not keep state, that is, be stateless, and in that case it would be the client that would have to send the necessary data.
When searching the internet and forums, I saw that it is common for developers to authenticate with JWT, where the client would make a request for a server’s route and the server would return a token, and through that token authentication would take place.
I even implemented something using
Firebase / jwt-php, where the client [Postman] makes a request for the route
/login sending via body [
password] and in case of success, returns the token to be used in secure route requests.
NOTE: Code is as simple as possible, without validation and cleaning just to show the example.
$username = $request->getParsedBody()['username']; $password = $request->getParsedBody()['password']; $userAuthenticated = ParseUser::logIn($username, $password); $payload = [ 'data' => $userAuthenticated, 'exp' => time() + 3600 ]; $token = JWT::encode($payload, $_ENV['JWT_SECRET_KEY']); echo json_encode(['token' => $token]);
And the protected routes have a
middleware that checks if the
time has expired, and if this has happened, an exception with a 401 code is launched.
So far so good, authentication works, the problem I don’t know if it’s right to do it this way, since I need to give a
ParseUser::logIn(), just to generate a session in the database and I don’t even use it this session to do some authentication, with the exception of operations in the bank, because from what I saw in the documentation, if there is no valid session in the database, the application will return
invalid session token error and also when making the request for another route
ParseUser::currentUser() returns null, and this may be a problem in the future.
Does anyone have any idea how I can implement authentication for a REST application made in PHP? I appreciate the help !!