【问题标题】:ASWebAuthenticationSession in SWIFTUISWIFTUI 中的 ASWebAuthenticationSession
【发布时间】:2020-01-19 21:43:54
【问题描述】:

我一直试图弄清楚如何将ASWebAuthenticationSession(通过Oauth 执行登录)与SwiftUI 集成。我在任何地方都找不到相同的在线文档,并且想知道是否有更多 SwiftUI 和 iOS 开发经验的人可以告诉我如何实现某些目标。我目前需要一个系统让某人单击登录按钮,然后打开一个ASWebAuthSession 并允许用户在将他们重定向回我的应用程序并加载另一个 SwiftUI 视图之前登录。

我的ContentView 中有一个调用此功能的按钮:

func getAuthTokenWithWebLogin() {

    let authURL = URL(string: "https://test-login.blabla.no/connect/authorize?scope=openid%20profile%20AppFramework%20offline_access&response_type=code&client_id=<blalblalba>&redirect_uri=https://integration-partner/post-login")
    let callbackUrlScheme = "no.blabla:/oauthdirect"

    webAuthSession = ASWebAuthenticationSession.init(url: authURL!, callbackURLScheme: callbackUrlScheme, completionHandler: { (callBack:URL?, error:Error?) in

        // handle auth response
        guard error == nil, let successURL = callBack else {
            return
        }

        let oauthToken = NSURLComponents(string: (successURL.absoluteString))?.queryItems?.filter({$0.name == "code"}).first

        // Do what you now that you've got the token, or use the callBack URL
        print(oauthToken ?? "No OAuth Token")
    })

    // Kick it off
    webAuthSession?.start()

}

但我收到此错误:

在不提供演示的情况下无法启动 ASWebAuthenticationSession 语境。在调用 -start 之前设置presentationContextProvider。

我应该如何在SwiftUI 中执行此操作?任何例子都会很棒!

【问题讨论】:

  • 我设法做到了这一点。但我遇到了一个新问题。我从服务器收到一条消息:[ERR] code_challenge 丢失。有人指出我缺少像 PKCE 这样的东西。

标签: swift swiftui ios13 xcode11


【解决方案1】:

BetterSafariView中使用.webAuthenticationSession(isPresented:content)修饰符,您可以在SwiftUI中轻松使用ASWebAuthenticationSession。它处理与提供演示上下文相关的工作。

import SwiftUI
import BetterSafariView

struct ContentView: View {
    
    @State private var startingWebAuthenticationSession = false
    
    var body: some View {
        Button("Start WebAuthenticationSession") {
            self.startingWebAuthenticationSession = true
        }
        .webAuthenticationSession(isPresented: $startingWebAuthenticationSession) {
            WebAuthenticationSession(
                url: URL(string: "https://github.com/login/oauth/authorize?client_id=\(clientID)")!,
                callbackURLScheme: "myapp"
            ) { callbackURL, error in
                print(callbackURL, error)
            }
        }
    }
}

【讨论】:

  • 我可以问你一个关于 github 上使用 swift ui 的 oauth 的问题吗?
猜你喜欢
  • 1970-01-01
  • 2020-02-02
  • 1970-01-01
  • 1970-01-01
  • 2020-03-16
  • 2020-08-11
  • 1970-01-01
  • 2019-10-23
  • 2019-03-23
相关资源
最近更新 更多