dimanche 1 janvier 2017

REST api - authentication methods (tokens?)

I am looking to learn creating REST APIs and one of the concepts I am struggling to get my head around is how to authenticate.

So for example I create a mobile phone app that allows users to sign up/login and store data about themselves.

Now, APIs will need to be created for returning their personal details as well as returning a list of associated orders - obviously these need to be secured in order to prevent users getting other people's details.

So I can easily pass into my API the user id and password in a post request and then compare this username and hashed and salted password on every request. But this means that these details are send with every request but wonder why this is a bad idea - is it because user password generally stay static and hardy change where as tokens will expire after so long?

So I have read about using tokens and I believe the concept goes something like this:

Send post request to get access token - this request will include a username and hashed and salted password. This will then be compared to the values in the database and then a 'token' will be generated and saved in the database and returned to the user.

So then in future requests we only 'post' the token within the body of the post (or should it be in the http header?) and then compare that in the database and this is used to authenticate the user.

Now I know that the token should expire fairly frequently (how often?) and a new one generated and used - but how should this be handled? E.g. if we want the user to permanently stayed logged into the mobile app unless they manually log out, the token will expire of course but how do I then generate a new one when they open the app again? do I send the user name and password only when the token has expired / does not exist?

Of course all of this will be over HTTPS.

Also what sort of things should trigger a token expiry? Is it things like a password change / no activity for a period?

What is the best method of generating a token, I know it needs to be fairy long and unique but what method is generally used to generate tokens?

Thanks for taking the time to read this.




Aucun commentaire:

Enregistrer un commentaire