---
title: "How do you sign in to a website with ASWebAuthenticationSession?"
description: "Use ASWebAuthenticationSession to run a web sign-in or OAuth flow in the system browser and receive the callback URL in your app. Includes working Swift code."
url: "https://bugsee.com/answers/swift/log-in-to-websites-with-aswebauthenticationsession/"
---

# How do you sign in to a website with ASWebAuthenticationSession?

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()`.

```swift
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

- [How do you read environment variables in Swift?](https://bugsee.com/answers/swift/swift-environment-variables/)
