Wednesday, January 31, 2018

Understanding SFSafariViewControllerDelegate and SFAuthenticationSession on IOS 11

SFSafariViewControllerDelegate 
SFSafariViewControllerDelegate has added the below new method in iOS 11
public func safariViewController(_ controller: SFSafariViewController, initialLoadDidRedirectTo URL: URL)
but Apple does not give much information in the API document.

One may attempt to use this method in oAuth library to handle redirect url after authorization is validated. However the testing shows this method is only called when a redirect (301) happens during loading the initial url in SFSafariViewController. After the page is loaded, any redirect (301) happened in following requests from client to server will not trigger this method. Probably that is why the method name is "initialLoadDidRedirectTo".

In addition, after initial load is done, if javascript uses a html form to post the page to a different host and port, or uses window.location to set to a different host and port, none of the operations will trigger this callback method.

The above behaviour pretty much makes the new method useless for oauth authentication and the traditional custom url scheme is still needed to handle the oauth authentication from mobile device.

By the way, the SFSafariViewController use the same cache mechanism as mobile Safari browser, so in order to delete the cached response, such as 301 (Permanent Moved), you will need to clear the cache from Mobile Safari settings page. Just delete and reinstall the application on your iOS device will not delete the cache for SFSafariViewController.

  
SFAuthenticationSession
For ios 11, SFAuthenticationSession is a good choice to handle oAuth. The important thing is set the callbackurlScheme parameter properly.

Although the parameter can be set to nil, which will rely the application open URL delegate method to handle the oauth result, but that really does not make sense, as the point of using this new method is avoiding defining custom url scheme and the related logic in application's openURL method.

The callbackurlScheme must be set to a custom schema, setting it to "http" or "https" will not work. In addition, the parameter must only contain the scheme, not a full url. For example, if the oauth redirect url is "sapbi://mypayload", then the parameter needs to be set as "sapbi" without any colon or slash.

It does not matter whether the custom url is loaded by redirect or by form submit, as long as webview tries to open the custom url, the callback method will be called. Once the callback method is called, then the webview will be automatically dismissed, so there is no need to explicitly call cancel in the completing block.

The biggest benefit of the SFAuthenticationSession for oauth is no longer required the app to define the custom URL scheme at compile time, the oauth redirect url can be changed at runtime when creating the SFAuthenticationSession object.

No comments:

Post a Comment