I am developing a small REST-webservice for non critical data which will mainly be accessed by a smartphone application. For limiting the access of the users to their individual data (the authorization does not need groups or roles), I need to implement some sort of basic authentification.
As the service will be accessed over HTTP, using HTTP-Authentification seems to be no good idea as the username and password will be sent in cleartext on every request and need to be stored on the client device.
Thus, my idea was to implement authentification the following way:
- The user logs on using a login method of my webservice passing their username / password
- This method checks the validity of the username / password combination (based on a database containing salted and hashed passwords)
- If the login is successful, the id of the user (primary key of the database table) is stored in the session as an attribute
- In the following requests, this attribute is used to authentificate the user
In code, my login method would look like the following:
User user = this.authentificate(username, password);
HttpSession session = request.getSession(true);
if (user != null)
session.setAttribute("UserId", user.getId());
else
session.invalidate();
Afterwards, I would be able to authentificate the user based on the session:
int userId = (int) request.getSession().getAttribute("UserId");
User currentUser = getUserById(userId);
Can this approach be considered as "secure" (no easy session highjacking possible - as far as I understood https://stackoverflow.com/a/5838191/232175 , the attributes' values won't leave the server)?
Are there any downsides or alternatives?