I'm currently writing a web service that will be consumed by an android app.
To access user specific content, one must authenticate against the service.
Since I'm not (primarily) using a webbrowser to make calls to my API, a solely session based authentication is not an option.
I don't want to pass the users credentials on every call either, so I decided to use a JWT[1] based authentication.
Edit: A few more details
The webservice is running on node.js.
The following modules play a key part in context to the question : express is used for the endpoints, passport for authentication, jwt-simple to generate tokens. Not directly relevant for the question but involved in the process is bcrypt-nodejs for encryption and sequelize to query the database, for which postgresql is used.
So far, the process looks the following - using example endpoints
- A first call is made to
/api/auth/login/
, passing along the username and the password of the authenticating user. - The api returns the users information stored in the database, along with a token. e.g.
{success: true, user: {id: 42, token: aaa.bbb.ccc}}
- Any subsequent request passes said token as a query parameter to authenticate the same user.
The question that rises now is: How do I correlate the token to a user and verify its validity.
The options I see are the following.
Since the token carries a payload, it's actually enough to put the users id into it and assume that if the token properly decodes it's valid and the API call will be made with privileges of the user whose id is contained in the payload.
- Since the token is encoded using a secret only known to the server, it shouldn't be possible to fake a token, unless someone gets its hands on the secret.
- other claims as
exp
oriat
can be included as well.
Upon generation of the token, it will be added to a
tokens
table which contains the token and its corresponding user id (id | user_id | token
). When a request is made, the database will be queried for existence of the token and only if an entry exists, itsuser_id
will be used.
Long story short, my question breaks down into these:
Is it necessary/sound to add the token to a database or can I just use the payload to identify the user?
Does it make any sense to change the servers secret - used to encode the token - about every week, hence invalidating any token generated previously?
- Using this approach an additional query against the database has to be made on every single request.
[1] - http://jwt.io/