Contents

WebAuthenticationSession

A SwiftUI environment value that views use to authenticate someone using a web service.

Declaration

@MainActor struct WebAuthenticationSession

Overview

You access an instance of this type by using the SwiftUI Environment property wrapper and specifying webAuthenticationSession as the environment value.

To begin an authentication session and display the browser, call authenticate(using:callbackURLScheme:preferredBrowserSession:). For example, when someone taps a button, the web service authenticates that person and then the authentication provider redirects the browser to a URL it constructs using the app’s custom callback scheme. The browser detects that redirect, dismisses itself, and returns the complete URL to the awaiting caller.

The following example shows how to use a SwiftUI Button to invoke a session:

struct WebAuthenticationSessionExample: View {
    // Get an instance of WebAuthenticationSession using SwiftUI's 
    // @Environment property wrapper.
    @Environment(\.webAuthenticationSession) private var webAuthenticationSession
    
    var body: some View {
        Button("Sign in") {
            Task {
                do {
                    // Perform the authentication and await the result.
                    let urlWithToken = try await webAuthenticationSession.authenticate(
                        using: URL("https://www.example.com")!,
                        callbackURLScheme: "x-example-app"
                    )
                    // Call the method that completes the authentication using the
                    // returned URL.
                    try await signIn(using: urlWithToken)
                } catch {
                    // Respond to any authorization errors. 
                }
            }
        }
    }
}

After receiving the URL, inspect it to determine the authentication request’s outcome. For example, you might search the URL’s query parameters for a token of some form:

let queryItems = URLComponents(string: urlWithToken.absoluteString)?.queryItems
let token = queryItems?.filter({ $0.name == "token" }).first?.value

Topics

Authenticating a session

Deprecated methods

See Also

Web authentication sessions