Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Token-based authentication from a mobile app

I am learning about Token-based authentication with JSON Web Tokens and here is how I see it now for a mobile app, built with, e.g. Swift:

  1. I can create an object inside the app using user input, like

    { username: "patrickbateman", password: "ismyknifesharp", role: "regular", ... }

  2. Then I can generate a JWT token from it with a library.

  3. Then I send it to a supported API endpoint, like /api/contacts/list. Or do I have to send login/password as they are to authenticate?
  4. Server somehow checks the token correctness. But how? Should this server-generated token be saved in the database and used as a key? Or do I have to generate the token on server each time I get a request from client and compare it to client token?
  5. Get and manage all the data I need.

Here are my conclusions:

  1. I don't need to send login/password pair to server to authenticate the user.
  2. I need to send token each time I need to get auth-only data.
  3. I should implement some algorithm that changes the generated token due to some factors, like time passing, so that to make tokens expirable.
  4. I should send the token inside headers, but not necessarily, as it can be done inside the body of the JSON requests.

Are these conclusions correct? What's the way to check token that client sends?

like image 767
Sergei Basharov Avatar asked Nov 11 '15 06:11

Sergei Basharov


1 Answers

My opinions:

  1. We should not keep password of user on client. Client should post password to server when sign up/ sign in, and don't save it anywhere in client. Request should be https, and password should not be encrypted. We will encrypt password later at server side.

  2. Server will generate a token for this user after user login successfully. The token will contain the expired date in itself. We will use the token to authenticate permission with server.

  3. I think every request to API should provide the token, except the sign up / sign in/ forgot password requests.

  4. Token should be put inside the header of request.

  5. Server should allow client request a new token with the old token (maybe be expired)

And the answer for "How to server check the token from client?". There are many ways to do that. The way below is my current approach:

Server side generate a token, which is a encrypted string of a user info (such as token expired time, userid, role... of user) and a password (keep only on server side) with HMAC or RSA algorithms. When user submit a token, server can decrypt and get the user info, expired time without querying from database.

Anyway, this question does not relate with Swift tag.

like image 113
t4nhpt Avatar answered Oct 11 '22 12:10

t4nhpt