How to put user authentication into a mobile application

后端 未结 1 540
无人及你
无人及你 2020-12-23 23:11

I\'m interested in the best way to do user auth in a mobile app. At the moment the set up is quite simple. I\'m storing the username and password on the app and sending it t

相关标签:
1条回答
  • 2020-12-23 23:51

    The correct way would be to generate auth token on the server when user logs and send this token in login reply. Then this token is used in subsequent requests.

    This means that server must keep track of auth tokens it generates. You can also track token creation times and make tokens expire after some time.

    Token must be a sufficiently long random string, so that it can not be easily guessed. How to do this was answered before: How to generate a random alpha-numeric string?

    Personally I prefer the UUID approach.

    Update:

    This problem was already solved in web browsers, via cookies and sessions. You can reuse this mechanism in your Android requests (though some REST purists disprove this approach):

    1. Enable sessions on server.

    2. When user logs into a server add some data to session, for instance time of login:

      request.getSession().setAttribute("timeOfLogin", System.currentTimeMillis());
      
    3. Since sessions are enabled, you also need to enable support for cookies in your HttpClient requests: Using Cookies across Activities when using HttpClient

    4. Every time a request is made, server should check if session contains timeOfLogin attribute. Otherwise it should return HTTP 401 reply.

    5. When user logs out, call server logout url and clear the cookies on client.

    0 讨论(0)
提交回复
热议问题