Skip to main content
Version: 1.x

iOS: Integrate Logto Swift SDK

note

This tutorial assumes you have created an Application of type "Native App" in Admin Console. If you are not ready, read this before continuing.

Add Logto SDK as a dependencyโ€‹

Use the following URL to add Logto SDK as a dependency in Swift Package Manager.

https://github.com/logto-io/swift.git

Since Xcode 11, you can directly import a Swift package w/o any additional tool.

We do not support Carthage and CocoaPods at the time due to some technical issues.

Carthage

Carthage needs a xcodeproj file to build, but swift package generate-xcodeproj will report a failure since we are using binary targets for native social plugins. We will try to find a workaround later.

CocoaPods

CocoaPods does not support local dependency and monorepo, thus it's hard to create a .podspec for this repo.

Init LogtoClientโ€‹

import Logto
import LogtoClient

let config = try? LogtoConfig(
endpoint: "<your-logto-endpoint>", // E.g. http://localhost:3001
appId: "<your-app-id>"
)
let client = LogtoClient(useConfig: config)

By default, we store credentials like ID Token and Refresh Token in the Keychain. Thus the user doesn't need to sign in again when he returns.

To turn off this behavior, set usingPersistStorage to false:

let config = try? LogtoConfig(
// ...
usingPersistStorage: false
)

Sign inโ€‹

Configure Redirect URIโ€‹

Let's switch to the Application details page of Admin Console in this section. Add a Redirect URI io.logto://callback and click "Save Changes".

Redirect URI in Admin Console

Redirect URI is an OAuth 2.0 concept which implies the location should redirect after authentication.

info

The Redirect URI in iOS SDK is only for internal use. There's NO NEED to add a Custom URL Scheme until a connector asks.

Sign in with browserโ€‹

note

Before calling .signInWithBrowser(redirectUri:), make sure you have correctly configured Redirect URI in Admin Console.

Go back to Xcode, use the following code to implement sign-in:

do {
try await client.signInWithBrowser(redirectUri: "io.logto://callback")
print(client.isAuthenticated) // true
} catch let error as LogtoClientErrors.SignIn {
// error occured during sign in
}

Sign outโ€‹

Calling .signOut() will clean all the Logto data in Keychain, if it has.

await client.signOut()

Fetch user informationโ€‹

Logto SDK helps you fetch the user information from the OIDC UserInfo Endpoint.

You can get the user information by calling logtoClient.fetchUserInfo() after signing in.

The user information response will vary based on the scopes used in the LogtoConfig while initializing the LogtoClient; and the following table lists the relations between user information and scopes:

Field NameTypeRequired ScopeNotes
substringopenidThe openid scope is added by default.
namestringprofileThe profile scope is added by default.
usernamestringprofileThe profile scope is added by default.
picturestringprofileThe profile scope is added by default.
emailstringemail
email_verifiedbooleanemail
phone_numberstringphone
phone_number_verifiedbooleanphone
custom_dataobjectcustom_data
identitiesobjectidentities

Backend API authorizationโ€‹

Logto also helps you apply authorization to your backend APIs . Please check our Protect your API see how to integrate Logto with your backend applications.

You can claim an authorization token for a protected API Resource request easily through Logto SDK.

info

In order to grant an audience restricted authorization token for your request, make sure the requested API Resource is registered in the Logto Admin Console.

Add your API resource indicators to the Logto SDK configs:

let config = try? LogtoConfig(
endpoint: "<your-logto-endpoint>", // E.g. http://localhost:3001
appId: "<your-app-id>",
resources: ["<your-resource-indicators>"]
)
let client = LogtoClient(useConfig: config)

Claim an authorization token from Logto before making your API request:

  let accessToken = try await client.getAccessToken(for: "<your-target-api-resource>")
// custom logic

With the user's authorization status, a JWT format access_token will be granted and issued by Logto, specifically for the requested API resource. Encrypted and audience-restricted with an expiration time. The token carries all the necessary info to represent the authority of this request.

Put the token in the Authorization field of HTTP headers with the Bearer format (Bearer YOUR_TOKEN), and you are good to go.

note

The Bearer Token's integration flow may vary based on the framework or requester you are using. Choose your own way to apply the request Authorization header.

await LogtoRequest.get(
useSession: session,
endpoint: userInfoEndpoint,
headers: ["Authorization": "Bearer \(accessToken)"]
)

Further readingsโ€‹