Swift : How to check if Facebook access token has expired? - swift

I'm currently using
if FBSDKAccessToken.currentAccessToken() != nil {
//Do Something
}
else {
//Passing the access token to my server
}
to check if a user is already logged in. But the problem in this approach is if a user opens my app after long time the currentAccessToken might have expired but since it is not nil it will send the expired token to the server.
How can I put a check if currentAccessToken is valid or not? I'm using version 2.4 of FBSDK

I think you may request https://graph.facebook.com/me?access_token=TOKEN
If token is not valid you will get oauth error in json response, otherwise you will get some info about user.
But better, for my mind, do the same on server side.

Related

Duplicated anonymous users when session expired in Parse platforms

if let cachedUser = PFUser.current() {
// proceed to save some objects
} else {
PFAnonymousUtils.logIn{ (user, error) in
// proceed to save some objects
if ((error as NSError).code == 209) {
// session expired, logout and call PFAnonymousUtils.logIn again later
PFUser.logOut()
}
}
}
For a simple Swift mobile app, we save data on parse backend anonymously. If there is session expiration error (1 year default on Parser server), we will have to do something about it or we wont be able to save anything anymore. We therefore logout and re-login again.
Once we logout and re-login again, this creates a second new User on the backend.
This creates a problem - we no longer have an accurate picture of the number of users on the backend.
What was wrong in the flow above? Is there a way to prevent duplicated anonymous user when handling expired session?
It is possible to increase the default session duration in your server configuration.
You can also add the code below to your server configuration...
expireInactiveSessions: false
This thread may provide further useful insights into this issue.

Is it a good practice to reload credentials before every request?

I'm working on an iOS app that works with a backend made in laravel, this api manage login and information exchange via JSON web tokens.
To prevent the user to access a web route with an expired token I check the user's credentials before every web call.
My question is, is it a good practice? Because when I started thinking about it the user is accessing twice the amount of times to my server.
For example this is the function to access they're information.
/// Get user's info form the database
///
/// - Parameter completed: Completition Block
func getInfo(completed: #escaping DownloadComplete){
let token = self.getToken()
print(self.getError())
if(token != nil && token != ""){
//Here is where I check credentials.
self.checkCredentials(completed: {
let url = "\(Base_URL)\(myInfo)\(self.getToken() ?? "")"
Alamofire.request(url, method: HTTPMethod.get).responseJSON { respone in
if let result = respone.result.value as? Dictionary<String, AnyObject>{
if let user = result["User"] as? Dictionary<String, AnyObject>{
var Info = Alumno()
if let id = user["id"] as? Int64!{
Info.id = id
}
...
self.userInfo = Info
completed()
}
}
}
})
}
}
The check credentials functions asks the server if the user's token is still valid and if it is it returns
{
"Status": "Success"
}
My answer assumes your server validates the token, and you are not relying on the app to validate the token.
With that assumption, I think it depends on what you can do if the token is expired.
If the only thing you can do is prompt the user to sign in again, then I would probably just make the web request and handle the 401 Not Authorized.
However, if you have the ability to silently refresh the user's token, you may want to preemptively refresh the token if is close to expiring.
In my application, before every web request the app checks if the user's access token will expire within the next 3 minutes, and if so, attempts to refresh it before making the request. If the refresh is successful, the web request is made with the new access token. If the refresh fails, the web request is not made and the app prompts the user to sign in instead. If for any reason the web request still fails after that with 401, the app prompts the user to sign in.
I would do it like once every time the user opens the app not every call.
Other options:
You could also give them a code that they enter that's good for so long.
You could have them sign in when they first download the app. Then they would always be logged in. Then when the token is expired a little popup would say "Something Something Something"

iOS Today Widget utilize Uber login token

I have an app with an Uber login that gives access to restricted API calls (info on the current ride). I'd like to share the login token with the associated Today Widget so it can make similar calls.
I'm already sharing data with a UserDefaults suite, and I'm using the UberRides SDK. In digging into the RidesClient object it seems to try to use the keychain for storing/sharing the login token, and I set up a shared keychain to try to take advantage of this, but no luck. Restricted API calls from the widget return as unauthorized. Any suggestions?
Here's some code from the widget (note the user already authenticated in the main app):
let rc = RidesClient()
rc.fetchCurrentRide { ride, response in
if ride == nil { print("NO CURRENT RIDE") }
print(response.response)
print(response.error?.title)
if let ride = ride {
// do something
} else {
self.ride = nil
}
}
This returns an unauthorized response. I traced into the RidesClient (which is an object in the UberRides SDK), and see the code where the token is "supposed" to come from the keychain, but it doesn't.
I also tried generating my own URL request in the widget, using the login token passed through shared UserDefaults. This followed the standard HTTP access approach, putting the token in the Authorization header. But I got the same unauthorized response.
Here's some more details on the SDK approach:
Main app uses the LoginButton in native mode:
let scopes: [RidesScope] = [.Profile, .Places, .Request, .AllTrips]
let loginManager = LoginManager(accessTokenIdentifier: Configuration.getDefaultAccessTokenIdentifier(), keychainAccessGroup: "com.MYCOMPANY.MYAPP.share", loginType: .native)
let loginButton = LoginButton(frame: loginFrame, scopes: scopes, loginManager: loginManager)
loginButton.presentingViewController = self
loginButton.delegate = self
view.addSubview(loginButton)
The login button does the right thing and authorizes in the Uber app. I can see the token returned in the delegate callback didCompleteLoginWithToken. However, I can then check for the token:
let token = TokenManager.fetchToken(Configuration.getDefaultAccessTokenIdentifier(), accessGroup: "com.MYCOMPANY.MYAPP.share")
print(token)
The token is "nil". I don't think the SDK is saving the token into the access group keychain.
When I use the default keychain (not the keychainAccessGroup), the login in the app works fine and I can get the login token back and make restricted calls to the API. However, that doesn't help the widget, which needs the token from the access group keychain.
Solved!! After many hours of debugging, and searching. What was not clear in ANY documentation is the keychainAccessGroup MUST include the AppIndentifierPrefix. That's the 10 character identifier associated with the App ID. So, instead of using "com.MYCOMPANY.MYAPP.share", it's "APPID.com.MYCOMPANY.MYAPP.share" for the keychainAccessGroup.

Parse user not updating for just one specific user

I was wondering if anyone has seen a case where Parse User table doesn't update for a specific user. I have a pretty simple code:
PFUser.current()?["TorF"] = true
PFUser.current()?.saveInBackground(block: { (success, error) in
if error != nil {
print(error)
} else {
}
})
I have checks in other places of the app regarding whether there is a current PFUser, and my database shows that the user is logged in and PFUser.current() is correctly assigned to this user. The simple operation above works for all other users except for one specific user. Has anyone encountered something like this?
I found out that this was happening because the user had changed his password and therefore invalidated his access token. The place to check for whether the user's access token is valid is via Graph request.

HWIOAuthBundle, how to manually authenticate User with a Facebook access token?

I have a website (Symfony2) with HWIOauthBundle used to connect with Facebook and everything works fine.
Now, I'm trying to build an iOS app with Cordova and Ionic framework (AngularJS) and I want to authenticate my user with Facebook :
With $cordovaFacebook, I authenticate my user and get a valid Facebook access token, that's ok
I try to use this access token to authenticate my user on the server-side with HWIOauthBundle :
GET http://..../login/facebook?code=MY_FACEBOOK_ACCESS_TOKEN
Symfony rejects my request with this log :
INFO - Matched route "facebook_login" (parameters: "_route": "facebook_login")
INFO - Authentication request failed: OAuth error: "Invalid verification code format."
So my question is : how can I authenticate my user on both front and back end with Facebook connect?
Thanks :)
I've also been wondering how to implement a server side login with the HWIOAuthBundle.
I didn't find any solution on the web, so I coded the functionnality based on hints I've read on the net.
Basically, you have to :
authenticate the user on your app
make an http request to your server with the Facebook token.
ont the server side, check if the token is for your Facebook app, and retrieve the user's Facebook ID.
Get your user from the DB based on the fetched ID.
Here's my Symfony controller:
public function getSecurityFbAction($token)
{
// Get the token's FB app info.
#$tokenAppResp = file_get_contents('https://graph.facebook.com/app/?access_token='.$token);
if (!$tokenAppResp) {
throw new AccessDeniedHttpException('Bad credentials.');
}
// Make sure it's the correct app.
$tokenApp = json_decode($tokenAppResp, true);
if (!$tokenApp || !isset($tokenApp['id']) || $tokenApp['id'] != $this->container->getParameter('oauth.facebook.id')) {
throw new AccessDeniedHttpException('Bad credentials.');
}
// Get the token's FB user info.
#$tokenUserResp = file_get_contents('https://graph.facebook.com/me/?access_token='.$token);
if (!$tokenUserResp) {
throw new AccessDeniedHttpException('Bad credentials.');
}
// Try to fetch user by it's token ID, create it otherwise.
$tokenUser = json_decode($tokenUserResp, true);
if (!$tokenUser || !isset($tokenUser['id'])) {
throw new AccessDeniedHttpException('Bad credentials.');
}
$userManager = $this->get('fos_user.user_manager');
$user = $userManager->findUserBy(array('facebookId' => $tokenUser['id']));
if (!$user) {
// Create user and store its facebookID.
}
// Return the user's JSON web token for future app<->server communications.
}
I throw the Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException exceptions to handle login errors on my app.
Of course, you really should use https because you will be exchanging sensible information.
I don't know if it's the best way to do it but it works well.
Hope it helps !
Well, I think that Symfony doesn't actually reject your request. Facebook is. I'm not sure if this might help, but I know that a bunch a problems can happen when dealing with the Facebook Auth :
Do you know if the tool sends, along with the code parameter, a redirect_uri parameter ? If so :
Did you check that your redirect_uri HAS a trailing slash at the end ? See this
Silly question, but did you check that your app_id is the same when you got authorized via Cordova ?
Check that your redirect_uri DOES NOT have any query parameter.
Check that the redirect_uri that you use during the whole process is the same all the time.
Overall, it seems that your issue is almost all the time related to the redirect_uri URI format.