> ## Documentation Index
> Fetch the complete documentation index at: https://docs.portalhq.io/llms.txt
> Use this file to discover all available pages before exploring further.

# completeOAuthLogin

> Completes a Google or Apple redirect from loginWithGoogle or loginWithApple and returns the resulting AuthResult.

**Function Signature**

```swift theme={null}
public func completeOAuthLogin(_ redirect: AuthRedirect.OAuth) async throws -> AuthResult
```

A `PortalAuth` method. Exchanges the grant of a `loginWithGoogle()` / `loginWithApple()` redirect. Pass the `.oauth` value [`parseRedirect`](./portalauthparseredirect) returned. [`signInWithGoogle`](./portalauthsigninwithgoogle) and [`signInWithApple`](./portalauthsigninwithapple) do all of this for you.

The grant is exchanged only with the code verifier of the sign-in this device started, so you can pass every `.oauth` redirect your app receives: one this device did not start signs nobody in. See [Google and Apple sign-ins are bound to the device](https://docs.portalhq.io/sdks/ios/guide/client-auth.md#google-and-apple-sign-ins-are-bound-to-the-device).

**Parameters**

* **`redirect`**: The `AuthRedirect.OAuth` from `parseRedirect`. `redirect.provider` is `.google` or `.apple`. Only `parseRedirect` can build one, and its grant token is not public.

**Returns**

* **`AuthResult`**: One of:
  * **`.authenticated(AuthenticatedResult)`**: The sign-in is complete. `session` is already saved to the Keychain; pass it to `Portal(credentials:)`.
  * **`.totpRequired(TotpRequiredResult)`**: A two-factor code is required. Nothing is persisted; complete the sign-in with [`verifyTotp`](./portalauthverifytotp).

**Throws**

* `PortalAuthError.oauthFlowNotStarted`: This device has no Google or Apple sign-in in progress for the redirect: none was started here, it already completed and is no longer remembered (an earlier launch, another instance, or after `clearPersistedSession()`), it is more than 15 minutes old, or `clearPersistedSession()` cancelled it. Raised before any network call, except when `clearPersistedSession()` on the same instance cancels the exchange while it runs (the grant may then be spent). Not retryable with the same redirect; start a new sign-in.
* `PortalRequestsError.unauthorized`: Portal refused the grant: it was already used, has expired, was issued for another environment, or its sign-in method has since been disabled — or it belongs to a sign-in other than the one in progress on this device, for example one a newer sign-in replaced. Also raised without a request when the remembered session has since ended. Not `PortalAuthError.grantRejected`, which is only for magic links. Start a new sign-in.
* `PortalAuthError.invalidGrantResponse`: The exchange returned neither a session token nor a `userJwt`.
* `PortalAuthError.malformedResponse(path:missing:)`: The response did not carry the documented fields.
* `PortalAuthError.sessionStorageFailure(message:)`: The Keychain failed this time. Either the sign-in in progress could not be read, in which case nothing was sent, or the grant was exchanged but the session could not be saved, in which case it is not returned. In both cases call `completeOAuthLogin` again with the same redirect on the same instance: the first retries the exchange, the second finishes the write without sending the grant again.
* Other transport errors unchanged.
* `CancellationError`: The calling task was already cancelled. Nothing is sent.

**Notes**

* **Bound to this device.** Only the sign-in this device started can complete: one at a time per auth environment, within 15 minutes, in this app. A sign-in started with `loginWithGoogle()` / `loginWithApple()` still completes if iOS terminated your app while the browser was open. Available starting from SDK version 8.2.0.
* **Exchanged successfully at most once per instance**, on the same terms as [`confirmMagicLink`](./portalauthconfirmmagiclink): concurrent calls with the same redirect run one at a time, so they share one successful exchange; a call after a successful one returns the remembered result — the same `PortalSession` instance — without a request, while that session is live; only the most recent sign-in is remembered, on this instance and in this process.
* A failed exchange is not remembered, so calling again sends the grant again; after a dropped connection or an HTTP error, the sign-in stays in progress for that retry. That succeeds only if the failed attempt never reached Portal; otherwise it throws `PortalRequestsError.unauthorized`. The exception is `.sessionStorageFailure` after the exchange, above. After `.invalidGrantResponse` or `.malformedResponse` the grant is spent, so a retry throws `oauthFlowNotStarted`.
* A Google or Apple sign-in must finish at the provider within 10 minutes and be exchanged within 15 minutes of starting. See [Grants are single use](https://docs.portalhq.io/resources/authentication/redirect-urls.md#grants-are-single-use).
* After the app is relaunched, a redirect delivered again for a completed sign-in fails, usually with `oauthFlowNotStarted`. Restore the session with [`restoreSession`](./portalauthrestoresession) instead.
* On success the session is persisted **before** it is returned.
* Cancellation is honoured only before the exchange starts; once it has started it runs to completion and the result is still returned and remembered. A `clearPersistedSession()` on the same instance cancels it instead: it throws `oauthFlowNotStarted` rather than return a session the clear is about to delete. One running on another instance completes, so if your app signed out while it ran, discard the result instead of adopting it.
* Anything you do with the result has to be safe to run twice, because a repeat call returns the same result.
* Available starting from SDK version 8.2.0.

**Example Usage**

```swift theme={null}
import PortalSwift

@MainActor
func completeOAuth(_ redirect: AuthRedirect.OAuth) async {
    // Your app's count of sign-outs (PortalHolder.signOutCount in the guide).
    let signOuts = signOutCount
    do {
        let result = try await auth.completeOAuthLogin(redirect)
        // Signed out while it ran: the session works in memory, but is not adopted.
        guard signOutCount == signOuts else { return }
        switch result {
        case .authenticated(let authenticated):
            adopt(authenticated.session)
        case .totpRequired(let step):
            presentTotpPrompt(step)
        }
    } catch PortalAuthError.oauthFlowNotStarted {
        // No sign-in in progress on this device for this redirect. Nothing was sent.
        showSignInError("That sign-in could not be completed. Please start a new sign-in.")
    } catch PortalRequestsError.unauthorized {
        // Refused by Portal, and final.
        showSignInError("That sign-in can no longer be completed. Please start a new sign-in.")
    } catch {
        // A dropped connection or a Keychain failure: the same redirect can be passed in again.
        showSignInError("Sign-in could not be completed. Please try again.")
    }
}
```

**Related Documentation**

* [parseRedirect reference](https://docs.portalhq.io/sdks/ios/reference/portalauthparseredirect.md)
* [loginWithGoogle reference](https://docs.portalhq.io/sdks/ios/reference/portalauthloginwithgoogle.md)
* [loginWithApple reference](https://docs.portalhq.io/sdks/ios/reference/portalauthloginwithapple.md)
* [Complete a Google or Apple sign-in](https://docs.portalhq.io/sdks/ios/guide/client-auth.md#complete-a-google-or-apple-sign-in)
* [Google and Apple sign-ins are bound to the device](https://docs.portalhq.io/sdks/ios/guide/client-auth.md#google-and-apple-sign-ins-are-bound-to-the-device)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.