Reputation: 67
I 'm building an app for my en of study project, and we want to add OAuth to some social networks and google. we have api roots built on our back, and to use this we need ASWebAuthenticationSession. So to connect with linkedin I do:
struct LoginView: View {
...
func loginWithProvider() {
guard let authURL = URL(string: "https://our.api.root/auth/linkedin") else {
return
}
let scheme = "oauth-linkedin"
let sessionWrapper = ASWebAuthenticationSessionWrapper(authURL: authURL, scheme: scheme) { callbackURL, error in
print("Authentication completed")
if let error = error {
print("Authentication error: \(error)")
} else if let callbackURL = callbackURL {
print("Callback URL: \(callbackURL)")
}
}
sessionWrapper.start()
}
}
class ASWebAuthenticationSessionWrapper: NSObject, ASWebAuthenticationPresentationContextProviding {
private var session: ASWebAuthenticationSession?
private let callback: (URL?, Error?) -> Void
init(authURL: URL, scheme: String, callback: @escaping (URL?, Error?) -> Void) {
self.callback = callback
super.init()
session = ASWebAuthenticationSession(url: authURL, callbackURLScheme: scheme) { url, error in
self.callback(url, error)
}
session?.presentationContextProvider = self
}
func start() {
session?.start()
}
func presentationAnchor(for session: ASWebAuthenticationSession) -> ASPresentationAnchor {
guard let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene else {
fatalError("No window scene available.")
}
guard let window = windowScene.windows.first else {
fatalError("No windows available.")
}
return window
}
}
struct LoginResponse: Codable {
let accessToken: String
}
The window opens, I can login and stuff. But then it sends us to our login web app page, keeps the browser overlay open, and when closing the overlay, we are still not connected.
Looking at logs I get:
Authentication completed
Authentication error: Error Domain=com.apple.AuthenticationServices.WebAuthenticationSession Code=1 "(null)"
update: the error comes from the fact I have to close the window myself to go back to the app. The real issue is that the callback url is sent to the web browser and not to the view itself.
Does someone here have an idea to fix this please?
Upvotes: 1
Views: 197