重定向 uri 在导航到 oauth 时导致问题 url

redirect uri causing issues when navigating to an oauth url

我正在尝试导航到 Microsoft Live oauth authentication 页面,以便我可以授权我的用户并获得应用程序使用的令牌。当我使用以下 NSURL 字符串时,我能够导航到该站点并授权我的应用程序,检索令牌。

let stringUrl = "https://login.live.com/oauth20_authorize.srf?client_id=\(clientId)&scope=\(scope)&response_type=code"
let url = NSURL(string: stringUrl)!

但是,我想重定向回我的应用程序(使用 SFSafariViewController)。为此,我向我的应用程序添加了一个 URL 方案,并将其作为 URL 中的 redirect_uri 传入。

let stringUrl = "https://login.live.com/oauth20_authorize.srf?client_id=\(clientId)&scope=\(scope)&response_type=code&redirect_uri=Lifestream://onedrive-oauth-callback"
let url = NSURL(string: stringUrl)!

但是 Live 登录站点给我一个错误,说出了点问题,无法继续。此错误发生在显示 oauth 登录页面之前。它在导航到 URL 时立即发生。

我是否错误地创建了 URL 方案,或者未正确地将方案传递给重定向 uri?我很困惑为什么它在没有 redirect_uri 的情况下工作正常,但是当我提供它时网站无法加载。

有人能给我指明正确的方向,告诉我应该如何将我的应用程序的重定向 url 传递到 oauth 重定向吗?

更新

Microsoft 似乎不允许您注册属于 App URL 方案的重定向 URL。我不知道如何将这些信息返回到我的应用程序中,除了为我可以指向 MSFT 的网站付费之外,除了为我重定向到应用程序之外什么都不做。

我有一个类似的 OAuth 问题并且不想弄乱网络服务器所以我所做的有点厚颜无耻。创建一个 UIWebView 并将请求放在 web 视图上。然后将它委托给自己并将重定向 URL 传递给 http://localhost:8000 (它可以是任何类似的东西,这真的无关紧要)。然后在委托内部执行此操作:

func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool
{
    if let URL = request.URL?.absoluteString
    {
        // This should be the redirect URL that you pass it can be anything like local host mentioned above.
        if URL.hasPrefix(redirectURL) 
        {
            // Now you can simply do some string manipulation to pull out the relevant components.
            // I'm not sure what sort of token or how you get it back but assuming the redirect URL is 
            // YourRedirectURL&code=ACCESS_TOKEN and you want access token heres how you would get it.
            var code : String?
            if let URLParams = request.URL?.query?.componentsSeparatedByString("&")
            {
                for param in URLParams
                {
                    let keyValue = param.componentsSeparatedByString("=")
                    let key = keyValue.first
                    if key == "code"
                    {
                        code = keyValue.last
                    }
                }
            }
            // Here if code != nil then it has the ACCESS_TOKEN and you are done! If its nil something went wrong.
            return false // So that the webview doesnt redirect to the dummy URL you passed.
        }
    }
    return true
}

这有点老套,但效果很好,您不需要任何服务器,也不需要在您的应用程序上使用重定向 URI,在我看来,这是一种很棒的实现方式。您可以针对 swift 2 进行优化,以通过使用守卫来减少缩进,但我在它出来之前就写了这个,所以...

希望对您有所帮助!