This nice tutorial is a very good introduction to account authentication on Android and doing it by utilizing Android's AccountManager.
However, I need to create a client app for an OAuth2 API using a Bearer token for authentication. At the time of obtaining the token, I receive the expiry timestamp for it, but I am unclear about where to store and how to make use of it properly. Problem is, if I don’t want to have unnecessary trips to the server, the app would realize that the Bearer had become invalid only after it receives a HTTP 401 error from the server when requesting any random resource. So, what is the best practice to tackle this:
- Should every network request in my code have a retry mechanism in case the bearer token has become invalid in meantime? I would probably
invalidateAuthTokenwhen catching the exception and retry. - Can Sync Adapter somehow help here?
As I am new to Android development, I expect that the solution may also be something completely different than I expect.
If it is relevant, I intend to use Volley for the server communication.
I found out my own answers after a bit of investigation:
Yes, calling
AccountManager#invalidateAuthTokenremoves the last saved authentication token (access token in the OAuth2 case) and expects that you are detecting that on the nextAccountAuthenticator#getAuthTokencall. For example, the following is my code for that method:I also received a confirmation from the author of the blog post mentioned in the question.
SyncAdapters cannot help directly, as their true purpose is obtaining data from network asynchronously (for the developer) and transparently (for the user). They just useAbstractAccountAuthenticatorand call its methods where appropriate.