Skip to content

API with only HTTP scheme into callback URL

Aakarsh Sasi edited this page Feb 5, 2020 · 7 revisions

Some API does'nt accept custom url scheme (ex: myapp://) into callback URL (ex: Linkedin oauth v2, Twitter oauth v1), only http is accepted

Two solutions

HTTP Redirect

Use an URL with http scheme, which redirect to your custom one

The demo use a web app for 'oauth-swift' URL scheme : http://oauthswift.herokuapp.com/callback/{path?query} which redirect to oauth-swift://oauth-callback/{path?query}

Code could be found here https://github.com/dongri/oauthswift.herokuapp.com

Or a simple php example:

<?php
function preserve_qs() {
    if (empty($_SERVER['QUERY_STRING']) && strpos($_SERVER['REQUEST_URI'], "?") === false) {
        return "";
    }
    return "?" . $_SERVER['QUERY_STRING'];
}
header("Status: 301 Moved Permanently");
header("Location: yourappname://oauth-swift/twitter" . preserve_qs());
?>

At https://apps.twitter.com/app/yourappid/settings (Twitter Developer App Settings), set your Callback URL to where you hosted this script.

For security reasons, you must host the code on your own server.

⚠️ for provider which use fragment to send token this could failed (ex: instagram), because fragment is not send to server

Handle a specific URL into delegate

Use an internal webview (UIWebView, WKWebView, ..)

  • by setting a controller as oauthswift.authorize_url_handler to load web pages into the webview
  • by implementing a web view delegate (UIWebViewDelegate, WKNavigationDelegate, ..) to handle the callback url and call OAuthSwift.handleOpenURL(url)

Example:

extension WebViewController: UIWebViewDelegate {
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebView.NavigationType) -> Bool {

            let urlString = request.url!.absoluteString
            let redirectUri = "YOUR_URL"
            if let _ =  urlString.range(of: "\(redirectUri)?code=") {
                OAuthSwift.handle(url: request.url!)
                self.dismissWebViewController()
            }
            return true
        }
}