How do you sign in to a website with ASWebAuthenticationSession?

← Swift answers

Create an ASWebAuthenticationSession with the sign-in URL and your app's callback URL scheme, give it a presentation anchor, keep a reference to it and call start().

import AuthenticationServices
 
final class WebLogin: NSObject, ASWebAuthenticationPresentationContextProviding {
    private var session: ASWebAuthenticationSession?
 
    func start() {
        let url = URL(string: "https://example.com/oauth/authorize?client_id=ID&response_type=code&redirect_uri=myapp://callback")!
 
        session = ASWebAuthenticationSession(url: url, callbackURLScheme: "myapp") { callbackURL, error in
            if let error = error as? ASWebAuthenticationSessionError, error.code == .canceledLogin {
                return // the user closed the sheet
            }
            guard let callbackURL, error == nil else { return }
            let items = URLComponents(url: callbackURL, resolvingAgainstBaseURL: false)?.queryItems
            let code = items?.first(where: { $0.name == "code" })?.value
            // exchange `code` for a token on your server
        }
        session?.presentationContextProvider = self
        session?.start()
    }
 
    func presentationAnchor(for session: ASWebAuthenticationSession) -> ASPresentationAnchor {
        let scene = UIApplication.shared.connectedScenes.first as? UIWindowScene
        return scene?.keyWindow ?? ASPresentationAnchor()
    }
}
  • The session must be kept in a property, or it is released and nothing appears.
  • The callback scheme (here myapp) must match the redirect URI registered with the provider.
  • The sheet shares cookies with Safari, so users who are already signed in skip the form. Set prefersEphemeralWebBrowserSession = true to avoid that.
  • Prefer the authorization code flow with PKCE, and never put a client secret in the app.

Related questions

Start debugging smarter today

Try Bugsee for free — no commitments, no hidden fees.

Free sign upLive demoNo credit card required