Reauthenticate after Session has expired in volley - android

I am new to the volley library and try to figure out what is the best way to do the following.
My REST Api uses Basic Authentication first and if succeed they return a Access Token to use from that point. Because my Acces Token can expire, this is a requirement.
I want to call my api method http://myserver/test
I get back a 401 (Unauthorized).
I want to call http://myserver/auth using basic authentication
I get back a Access Token
Set the header to "Authentication: Session " + AccessToken
I want to "retry" the request to http://myserver/test.
Update
So basically what i want to do is. If a request failed with a given status code, i want to do a other request and after that retry the first one.
Thanks in advance!

I am using a similar approach using Volley.
Have listener from where the request is sent., Everytime when you get response check for session, if session is expired, save existing listeners temporarily.
Create new listeners & get Token, if success, resend request with oldTemp Listeners, so the request is sent back to original request.
Working app in PlayStore with similar approach.

Related

Need to call an api to refresh token in android mvvm using retrofit ,where to write the logic?

At the time of login we get a authorization token and a refresh token,authorization token is attached with all API in header ,but after some time authorization token will expire and we will get 401,to refresh we need to call a API with refresh token that we get at the time of login in response we will get a new authorization token and refresh token,problem is where to catch 401 and write at one point to call refresh token API and resend the previous failed API ,we cant call API in interceptor.
Check this Refresh Access Token globally (Separate logic as a module) using RxJava 2, RxAndroid 2 and Retrofit 2 post.
Maybe it will help you
Okhttp (which acts as the http layer of retrofit) has a mechanism for doing just this. Have a look at https://square.github.io/okhttp/4.x/okhttp/okhttp3/-authenticator/
You provide the Authenticator to your Okhttp builder during setup and this then responds to 401 error responses to fetch a refresh token.

How to re use access token for future request and how to refresh access token Android Outlook API

In the example OutlookQuickStart for Android works fine in the first request after logon().Now I want to keep connect my app to that user and continue checking for new emails.. How can I re use the access token and build the request to check for new emails? Do I have to save the access token, refresh token ?
How I can refresh the token in Android if it is expired.
According to the documentation for the auth library at https://github.com/AzureAD/azure-activedirectory-library-for-android, the library caches the token and refresh token for you. So you would just use acquireTokenSilentSync to get the token each time you need it. That function would return the current token from the cache if it is still valid, and would refresh it if it is expired.
UPDATE: I've taken a closer look at the sample you're using and the Outlook SDK that it uses. The key thing here is the DependencyResolver object. You pass that object to the OutlookClient constructor. Then anytime you make an API call with that OutlookClient, it just calls the getCredentials override that you supply when you create the DependencyResolver.
So as the sample stands, you should be able to make multiple calls through that OutlookClient without having to change it at all. However, after an hour, when the access token expires, calls will start to fail. The fix for that would be to change the getCredentials override to always call acquireTokenSilentSync. Something like:
#Override
public Credentials getCredentials() {
logger.debug("getCredentials in resolver called");
AuthenticationResult result = mAuthContext.acquireTokenSilentSync(
scopes,
getResources().getString(R.string.AADClientId),
UserIdentifier.getAnyUser());
logger.debug("AcquireTokenSilentSync SUCCESS");
logger.debug("Token expires: ", result.getExpiresOn());
logger.debug("Token: ", result.getAccessToken());
return new OAuthCredentials(result.getAccessToken());
}
Caveat: I'm unable to run this code to validate it due to problems getting the Android emulator running on my dev machine :(.

What is the best way to add and check authorization token?

I am implementing an android application which will validate user details against the server and stores the return token. For subsequent requests it should send the token along with each request. Here are some of the points I need to consider.
I am using Retrofit 2 library to send http requests to the server
The token will be generated by JWT library and sent back to the client
If the token is not present or invalid or expired, the server will throw 400/401 error
Design
The landing page of android app is not login protected so that user can see the app before using his credentials
Once he is on MainActivity, any requests to other screens require authentication. So all other activities will check for token and redirect to login activity.
In case any response received from server has 400/401 header, it should also redirect to login page.
Considering the above requirements, I tried to add an interceptor in Retrofit service generator class which which will be executed on every request/response.
Problem
The interceptor is executed for every request not just once per activity. i.e. it is opening n number of logic activities if there are n number of async calls in the main activity (because no token will be present for all those requests).
Can someone help me in identify:
If there is a better design that can avoid such problem or
Is there any way to suspend main activity until login is completed and then resume it.

Best way to handle 401 errors with spring android

I have an android app which uses the spring android library to communicate with my restful api. I'm not sure how to handle the scenario when the token for my client expires. What I'd like to to is to capture any 401 error and simply fetch a new token and retry the request.
I've created a ResponseErrorHandler and wired that up to my rest template:
public class UnauthorizedErrorHandler implements ResponseErrorHandler {
....
public void handleError(ClientHttpResponse response) throws IOException {
if (response.getStatusCode().value() == HttpStatus.SC_UNAUTHORIZED) { // 401 error
// fetch a new token
// Retry request now that we have a new token????
}
}
}
My problem is that I have no access to the originating request in the Response error handler. Unless I'm missing something, this strategy seems reasonable, but I'm not sure how to make it work. This also seems like a typical scenario for any client that is working with OAuth tokens, so hopefully someone out there can point me in the right direction.
If the token has expired then you should ask the user to login again.
Think about a user removing your OAuth app access, your app will received an expired token or similar error, and you should have the user login and give your app access again.
If you are not referring to an OAuth token, but your own API, then your should create some sort of mechanism to update the token to be used by the client. For example, you can send a header with the new token on your response asking the user to start using the new value from that point onwards, or as part of the response body or a push notification requesting a token exchange, etc.

Dealing with expired auth token android account manager

Should I be invalidating and requesting a new token every time I need to make a request using a Google auth token from the AccountManager or is there an 'expired-at' time stamp I can use to see if it is still valid.
There is no expiry time provided in the HTTP response from the Google service, so I think you need to ensure that if the auth-token fails to provide access, you use that as the trigger to get a new auth token. Or you could acquire a new token each time the application starts, or create your own timeout.
http://code.google.com/apis/accounts/docs/AuthForInstalledApps.html
Looking at the HTTP response, the status code is 302 (it's redirecting you to provide auth token) and the "Set-Cookie" field in the header is not present. You could key off that.
if (res.getStatusLine().getStatusCode() == 302 && res.getHeaders("Set-Cookie").length == 0) {
// we need a new token
// invalidate account manager logic here
}
Failing to get that cookie from Google seems to signify it's time to grab a new token from AccountManager.
As there is no accepted answer yet:
I do it by firing my requests in a try block, then catching any exceptions and check if it's a 401 with if (e.getMessage().equals("401 Unauthorized")) { ... }.
Then, invalidate the auth token, request a new one and retry the request.
You need to call invalidateAuthToken(String, String) when you know the token has expired. i.e. when the request fails with an authentication error.

Categories

Resources