How to make to manage token refresh in app ios - ios

I have a web site where I have built a API Rest for IOS app. The app is composed from a Tab bar with two views the first view show the view of WELCOME or LIST OF EVENTS it depends on if user is logged or no, and the second view show the LOGINVIEW. I have built the method on server that check if the token is valid yet in the time so that if the user has already made the login in the app, when the token will expire, I would like that the app would has to do a refresh token (by call to the server tokenIsAlive the response NO and it would make autoLogin in background) using the credential saved in the NSUserdefault in the device. But I would like that the refresh token would has to be hidden (background) so that the app can show the views where require the authenticated user. I have used AFNetworking but how can I make to refresh token hidden? Which way would be advised to check if the token is not expire?
Does it to do for each call (getEvent,getListEvents,updateEvent..ecc) to the server, or only into the method
(void)applicationDidBecomeActive:(UIApplication *)application
?

The easiest approach is to set an NSTimer to call a method that does the refreshing after a set time interval (depending on the expiry time of the token). Also, set the timer's repeat property to TRUE. This way, the token remains fresh and does not expire unless the user logs out. When the user logs out,make sure you invalidate the timer and stop refreshing the token.

Related

swift: auto logout after certain time

I am developing an app which is connected to a server through .net api.
What user logs in it generate an access token which is used to make network calls.
Requirement: After 20 mins of the generation of that access token, the
token gets expired and the user have to log in again to continue using
the app.
How can I achieve this feature that after 20 min the user will get logout from app and redirected to the home page.
If the user is using app even after 20 min from login? how to save the access token in app and remove it once user logout.
I have seen a couple of answers in Objective c but I want the answer in swift.
Save your access token to the keychain, and timestamp it.
Write a function which gets you the API token from the keychain. Each time this function accesses the access token, it should check if its timestamp is older than 20 mins it should return nil, and then you shoudl take the user to the home screen.
Welcome to stack overflow
Short Answer
Create a timer in app delegate to track the token expiry. And reset timer when needed.
Long Answer TLDR;
To implement the feature as you have explained we need to
Keep track of access token expiry in app delegate only.
Start a timer for 20 mins when user logs in from AppDelegate.
Before making any API Calls access the token from app delegate (Internally you can save in any secure method for example KeyChain),
While accessing token from app Delegate check if timer is expired. If so present your login screen in the window.
If not present then make API Call and let the user do the tasks.
Advantage of this method
If you are sure that access token will expire in 20mins then without making any API calls we can logout the user from app.

MVC prevent reauthentication

I have an issue which plays out as follows:
When my users use my MVC app, they keep a particular page open most of the time as it is for logging phone calls. So the logging screen remains open, they then take a call and enter all the information, and then submit, but then if there was a fair gap between phone calls, then the token expires and they need to reauthenticate which redirects them to microsoftonline which then loses the data they had input.
Therefore is there any way to either prevent the reauthentication so that the controller can be accessed or perform a token refresh before the submit is performed in order for it to go through authenticated.
Im not sure what information will be of help to solve this so if i can provide any snippets etc to help please say and ill upload them immediately.
Thanks.
You have two options:
Set a custom session duration for your app's session cookies: to do this, you'll need to ensure that OWIN is not overwriting the session cookie lifetime (see link below for how to use OpenIdConnectAuthenticationOptions to do this).
Add session renewing logic to your app: one way to do this is with an iframe a route in your app that generates an authorization request.
Vittorio goes into this in detail in his blog post: Controlling a Web App's session duration.

How can I get access token with refresh token automatically for iOS/swift?(every hour)

Now I'm connecting my iOS app with server.
For use the server in the app, the app need Access Token.
When user logs in, they get Access Token with Refresh Token.
So after logged in, users don't need to log in anymore. And users can use the app without logging like instagram or facebook.
But the app must update/renew access token by using refresh token every hour,
because access token expires in 3600seconds(1hour).
But how can I query/update refresh token/access token every hour?
I think the app do this every hour automatically even in background.
now I can get access token using Alamofire.
But I'm not used to use connect server with app.
My app is for iOS and coded with Swift.
When the app is first opened by the user (comes to the foreground) you can refresh, then start a timer, say for 55 minutes. When the timer expires you can refresh. When the application goes to the background destroy the timer. Don't expect that the application should run a refresh in the background, it shouldn't and it has no reason to.
The above is all you need to do. When the app comes to the foreground you can instead check how much longer your current token is valid for and decide to not refresh and start a timer for N-5 minutes instead. And you can think about how to deal with refresh failures and no internet connection by changing the timer to run each minute perhaps...

How to check user auth on each viewcontroller that requires login?

OK...so I have a swift app that connects to a PHP backend. The user logs in, it stores a session on the server and sets an encrypted cookie in the cookieStorage on the app (I also store that cookie in keychain since cookieStorage can be volatile from what I'm told). I also store the username and password in keychain as well.
The session on the server expires after a time of non-use (let's say 30 days), but if the user comes back, the session renews itself if it's under 30 days old. So for example...lets say I don't come back for 15 days...my session is now reset to 1 day old and again has 30 days to expiration...however, if I come back on day 31, I have to re-login on the web app.
There are several viewcontrollers in this app that require the user to be logged in (a couple are uiwebviews that use the cookie to access the data on the server...those aren't a problem as they handle the sessions like a champ by default). The native views (tableview, etc) that require the user be logged in however are a different story.
Currently, on login, I set a switch in NSUserDefaults that the user is logged in...in didFinishLaunchingWithOptions, I just check to make sure the user is logged in...if they are logged in, we move them into the "private" area of the app, if they aren't logged in, we move them to the login screen (or signup screen).
All of this is fine and good...but with the sessions expiring on the server, I was wondering what is an appropriate way of handling this in an iOS app? I want them to stay logged in until they choose otherwise, but if the app stays closed for 31 days, the session on the server will no longer be valid. I was thinking that I could set a date in UserDefaults (last time app was opened) or something like that, and if they haven't opened the app in over 30 days, then I could just use the username and password stored in keychain to re-log them into the PHP backend and refresh their session and reset the stored login date (if the password is no longer valid, I would of course redirect to login view).
Is there a more appropriate way to handle this in an iOS app or does that sound like a valid approach? Should the date/session check be in didFinishLaunchingWithOptions and also in applicationDidBecomeActive ?
First, don't store anything that has to do with the login state in the userDefaults it's not secure.
Second, since you are storing the username and password in the keychain, why don't you just check the keychain and log the user in every time they open the app. This will give the user a persistent login until they log out then you can clear the keychain. Also this will give you another analytic point you can store in your database so you know every time the user opens your app.
Is there a reason you want to have a 30 day expiration?

Obtain NEW Apple device token?

I am creating an app that allows the user to log out of the app and log in as different user if they want to. Is there any way to obtain a new device token from Apple once the new user logs in? Is there a way to force call the didRegisterForRemoteNotificationsWithDeviceToken method?
No, you can't request a new device token. They expire from time to time, and only then will you get a new one (or if you have a different app with a different bundle id, the token will be different).
Create a function to handle didRegister and call that from didRegisterForRemoteNotificationsWithDeviceToken. Then use that function when you need to force the call.
Since users are logging in, pass the information with the device token to the server every time someone logs in and associate the user to the token on the server side.
There is no way to get a different device token. You need to remove the token from the backend when the user logs out.
I'm not sure how it behaves in iOS7 and later, but prior to iOS7, all applications on the same device would get the same device token, and therefore what you ask is impossible. As of iOS7, each application gets its own device token, but I'm not sure if that token can change on consecutive registrations.
You can always force call the didRegisterForRemoteNotificationsWithDeviceToken by calling registerForRemoteNotificationTypes, but usually you'll get the same device token.
If the goal is to associate notifications with specific users, then as of iOS 10, you can try implementing a NotificationService extension to filter only those notifications associated with the currently authenticated user. While multiple users on the same device will be associated with the same device token at the server, the client will only display notifications for the current user - assuming that only one user at a time can be logged-in.
This approach also allows for having notifications that don't require authentication - just pass those through unaltered.
As mentioned above, you can force a request-response token update after user login by explicitly calling UIApplication.shared.registerForRemoteNotification (Swift 3+). Then send that user+device token combination to your application server for use.

Resources