After creating a basic REST service, I’ve have come to the point where it would be appropriate to add some sort of password protection, as I need to verify that my users are both properly logged and have sufficient permissions to execute whatever action they are going to.
The REST service will mainly be accessed from a Javascript-heavy frontend and with that in mind, I have come up with the two following alternatives to solve this:
-
Make users login by first sending credentials to a
/loginpage withPOST. The page sets a session cookie wherein the user is
marked as logged in, along with the permission level. On each
following request, I verify that the user is logged in and his/her
permission level. When the session expires, automatically or
manually (logout, the user will have to re-logon). -
Temporarily save the credentials hashed locally and send the users credentials along every single request made by the user to verify the credentials & permissions backend on a per-request basis.
Are there more ways to solve this and is there something else that I should be concerned with?
I’m currently developing a REST API along with a client (written in javascript), below I’ll try to explain the methods used to protect the API against unauthorized access.
Make your REST API to require a
Auth-Keyheader upon every request to the API, besides/api/authenticate./api/authenticatewill take a username and a password (sent usingPOST), and return user information along side with theAuth-Key.This
Auth-Keyis randomly generated after a call to/api/authenticateand stored in the backenduserstable with the specific user entry, amd5hash of the remote ip + the user agent provided by the client.On every request the value of
Auth-Key, and themd5sum mentioned, is searched for inusers. If a valid user is found that has been active during the pastNminutes the user will be granted access, if not: http return code 401.In the REST client, first get the
Auth-Keyby posting to/api/authenticate, then store this value in a variable and send in on every future request.