Question

I have an app with an optional login where some functionality requires the user to login.

When checking if the user is logged in I use a framework that runs an async function that requests an access token from the keychain or our server (depending on if the token needs refreshing) with a completion block telling us what to do with that information. What is the best practise for using a function like this?

  1. Check if the user is loggedIn when they first open the app (or bring it to the foreground) and set their login status to a global flag
  2. Check if the user is loggedIn when a viewController that may require authentication loads and set it to a local flag
  3. Call the frameworks function directly when it is needed

The first approach I fear will be inaccurate and may require I store the users accessKey in a global variable. The third approach the user will have to wait until our token request is finished.

Était-ce utile?

La solution

Personally I do the following:

  1. User logs into app (or not) - an auth token (generated/stored on the server) is (also) stored locally if they log in successfully

  2. Any feature that requires a login (token) checks local storage first; if there is no token, prompt to login - if there is a token attempt the authenticated request

  3. If the user has a (presumably valid) token and the authenticated request fails, simply “expire” the local session (clear data) and prompt with a login request with something like “session expired” as a notification

  4. Otherwise all requests have a valid token and submit/finish normally

Step 3 is the important one. Check the cache and if there is a token, try the request. If it fails, the token may have expired, be fake, be expired, been tampered with, etc. But in any case, your server should be the important part of this step. It needs to validate tokens and respond properly in case of an invalid one.

Cache things and use the cache, but check server-side for token issues, and issue the correct response so that the app can “catch” the error and prompt for a re-authentication.

Once you have the above in place, you can check the local cache isLoggedIn() (or whatever you have) as often as required (for every feature/action that requires authentication).

Autres conseils

Where you have an Access and Refresh token, usually the refresh token will have a long expiry period.

You need only ask the user to login when that refresh token expires. Which can be days or even months.

I would suggest that you check the expiry date when the user launches the app and ask them to re-login if the token has expired or you think the token would expire while they are using the application. ie the token is about to expire.

Hopefully this will mean that your user is rarely prompted to login, and when they are it is when they launch the app, rather than in the middle of a process.

Licencié sous: CC-BY-SA avec attribution
scroll top