Instagram user authentication on iOS: specifying redirect_uri

I am developing an iOS application (using Swift) that allows a user to authenticate through Instagram using OAuth 2.0

In the past, everything worked fine, as I was able to specify the authorization URL as such: https://api.instagram.com/oauth/authorize/?client_id=xxx&redirect_uri=myiosapp://authorize&response_type=code

The key point here is redirect_uri myiosapp://authorize

My problem is that I can no longer register a custom URL scheme using Instagram, thereby making it impossible (?) To handle redirects exclusively through my application. If I try to add such a URI to the "Valid redirect URIs:" field, I get the following error:

You must enter an absolute URI that starts with http:// or https://

What is the recommended way to handle authentication using Instagram exclusively for the native iOS application?

+6
source share
1 answer

After finding out this, I thought that I would send my solution to everyone who is facing the same problem.

First of all, I just agree that Instagram no longer allows you to configure schemes in the "Security" β†’ "Valid URI redirects" field. Instead, I will introduce an arbitrary but valid URI that I can uniquely identify. For example: http://www.mywebsite.com/instagram_auth_ios

Now, when I try to authorize using Instagram, I will use this as a redirect URI - even if there is no web page in this URI. Example: https://api.instagram.com/oauth/authorize/?client_id=xxx&redirect_uri=http://www.mywebsite.com/instagram_auth_ios&response_type=code

Finally, I will use the UIWebViewDelegate shouldStartLoadWithRequest method to intercept the redirect request before it starts and will instead call my original user uri (so I don't have to rewrite anything). Here is how I wrote this method:

 func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool { guard let url = request.URL where url.host == "www.mywebsite.com" && url.path == "/instagram_auth_ios" else { return true } guard let authUrl = NSURLComponents(URL: url, resolvingAgainstBaseURL: false) else { return true } // Customize the scheme/host/path, etc. as desired for your app authUrl.scheme = "myappschema" authUrl.host = "instagram" authUrl.path = "" UIApplication.sharedApplication().openURL(authUrl.URL!) return false } 

There is one small caution with returning false in the shouldStartLoadWithRequest method, in which it will always complain about the error "Error loading frame." This does not seem to have a negative effect on anything and can (possibly) be safely ignored.

+8
source

All Articles