Skip to content
  • SDKs and APIs
  • Native app SDKs

iOS SDK

The Kinde iOS SDK allows developers to quickly and securely integrate a new or existing application into the Kinde platform.

You can view the Kinde iOS SDK and iOS starter kit in GitHub.

  • A Kinde account (Sign up for free)
  • iOS 13.0 or later
  • Swift 5.0 or later

KindeSDK is available through CocoaPods. To install it, add the following line to your Podfile:

pod 'KindeSDK'

Please note that KindeSDK is typically used with CocoaPods dynamic linking (use_frameworks!), as it takes a dependency on AppAuth.

If integrating with other pods that require static linking, follow the instructions provided by CocoaPods.

Kinde configuration

Link to this section

1. Create a Kinde application

Link to this section
  1. Go to your Kinde dashboard and select Add application.
  2. In Customer identity select Add application.
  3. Enter a name for the application (e.g., “My iOS App”), select Front end and mobile, and select Save.
  4. Select iOS and select Save.

2. Get app keys

Link to this section
  1. Open the application page you just created.

  2. Go to the Details page and scroll to the App keys section and copy:

    • Domain — the domain issued by Kinde (<your-business>.kinde.com), or Custom domain if you have configured a custom domain
    • Client ID

3. Set callback URLs

Link to this section
  1. On your application Details page scroll down to the Callback URLs section.

  2. Add your callback URLs in the relevant fields. For example:

    • Allowed callback URLs (also known as redirect URIs): <your_url_scheme>://kinde_callback
    • Allowed logout redirect URLs: <your_url_scheme>://kinde_logoutcallback
  3. Select Save.

Configuring your app

Link to this section

Custom URL Scheme

Link to this section

Register a custom URL scheme using one of these methods:

  1. Open your project in Xcode and select the project in the navigator.
  2. Under Targets, select your app target.
  3. Open the Info tab, expand URL Types, and select + to add a URL type.
  4. Set Role to Editor.
  5. Add <your-url-scheme> to URL Schemes.

For more information, see Apple’s Defining a custom URL scheme for your app.

Link to this section

Configure Universal Links to allow HTTPS links, such as https://example.com/login, to open your app:

  1. Open your project in Xcode and select the project in the navigator.

  2. Under Targets, select your app target.

  3. Open the Signing & Capabilities tab, select + Capability, and add Associated Domains.

  4. Add an entry for your URL’s domain:

    applinks:example.com

    Replace example.com with your domain. Don’t include https://, a path, or a trailing slash.

  5. Create an apple-app-site-association file, without a file extension, and host it at:

    https://<your-domain>/.well-known/apple-app-site-association

    Replace <your-domain> with the domain you added to Associated Domains. For example, if your domain is example.com, host the file at:

    https://example.com/.well-known/apple-app-site-association

    Add an applinks configuration that identifies your app and matches the URL path your app handles:

    apple-app-site-association
    {
    "applinks": {
    "details": [
    {
    "appIDs": ["ABCDE12345.com.example.App"],
    "components": [
    {
    "/": "/login"
    }
    ]
    }
    ]
    }
    }

    Replace:

    • ABCDE12345.com.example.App with your app’s application identifier, in the format <App ID prefix>.<Bundle ID>. Find these values in your Apple Developer account under Certificates, Identifiers & Profiles > Identifiers, then select your app.
    • /login with the URL path your app handles. This example matches https://example.com/login, including URLs with query parameters.

    Serve the file over HTTPS with a valid certificate and no redirects.

For full setup instructions, see Apple’s Supporting associated domains.

Environment variables

Link to this section

The Kinde Auth service is configured with an instance of the Config class. The example uses the bundled kinde-auth.json for configuration.

To get the details, go to Settings > Applications > [your app] > View details. Then scroll to the App keys section.

  • issuer: your Kinde domain
  • clientId - you can find this on the Application details page
  • redirectUri (Allowed callback URL): After the user authenticates we will callback to this address. Make sure this URL is under your allowed callback URLs.
  • postLogoutRedirectUri (Allowed logout redirect URL): where you want users to be redirected to after logging out. Make sure this URL is under your allowed logout redirect URLs.
{
"issuer": "https://<your-business>.kinde.com",
"clientId": "<your-client-id>",
"redirectUri": "<your-url-scheme>://kinde_callback",
"postLogoutRedirectUri": "<your-url-scheme>://kinde_logoutcallback",
"scope": "offline openid email profile"
}

Replace the values in <angle brackets> with your own values. For example:

{
"issuer": "https://app.kinde.com",
"clientId": "abc@live",
"redirectUri": "com.example.App://kinde_callback",
"postLogoutRedirectUri": "com.example.App://kinde_logoutcallback",
"scope": "offline openid email profile"
}

Integrate with your app

Link to this section

Before using KindeSDKAPI.auth or other Kinde SDK APIs, call KindeSDKAPI.configure() during app initialization.

Initialize Kinde in the init() of your @main app.

MyApp.swift
import SwiftUI
import KindeSDK
@main
struct MyApp: App {
init() {
KindeSDKAPI.configure()
}
var body: some Scene {
WindowGroup {
ContentView()
}
}
}

For UIKit apps both with and without a scene delegate, you can initialize Kinde in your app delegate’s application(_:didFinishLaunchingWithOptions:) method.

AppDelegate.swift
import UIKit
import KindeSDK
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions:
[UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
KindeSDKAPI.configure()
return true
}
}

Multiple environments

Link to this section

You can configure your app to use different Kinde environments, such as development, staging, and production.

Set up environments in Kinde

Link to this section

Create each environment in your Kinde dashboard, then create an application in each one. Each application has its own issuer, clientId, and callback URLs. For setup steps and plan limits, see Environments.

Configure environments in your app

Link to this section

Create a JSON config file for each environment in your project, for example kinde-auth-production.json and kinde-auth-development.json. Each file uses the same format as kinde-auth.json, with the details for that environment:

{
"issuer": "https://<your-business>.kinde.com",
"clientId": "<your-client-id>",
"redirectUri": "<your-url-scheme>://kinde_callback",
"postLogoutRedirectUri": "<your-url-scheme>://kinde_logoutcallback",
"scope": "offline openid email profile"
}

Pass the file name (without the .json extension) to KindeSDKAPI.configure() to choose the environment:

// Production
KindeSDKAPI.configure(fileName: "kinde-auth-production")
// Development
KindeSDKAPI.configure(fileName: "kinde-auth-development")

Custom Logger (Optional)

Link to this section

Calling KindeSDKAPI.configure() without a logger uses the SDK’s DefaultLogger.

To customize logging, create a type that conforms to LoggerProtocol:

CustomLogger.swift
import KindeSDK
struct CustomLogger: LoggerProtocol {
func debug(message: String) {
print("[DEBUG]: \(message)")
}
func info(message: String) {
print("[INFO]: \(message)")
}
func error(message: String) {
print("[ERROR]: \(message)")
}
func fault(message: String) {
print("[FAULT]: \(message)")
}
}

During app initialization, pass your custom logger to KindeSDKAPI.configure():

KindeSDKAPI.configure(CustomLogger())

Login and register

Link to this section

The Kinde client provides methods for an easy to implement login / register flow.

You can add buttons in your view as follows: (we’re using UIKit).

...
import KindeSDK
...
override func viewDidLoad() {
...
view.addSubview(signInButton)
view.addSubview(signUpButton)
signInButton.addTarget(self, action: #selector(signIn), for: .primaryActionTriggered)
signUpButton.addTarget(self, action: #selector(register), for: .primaryActionTriggered)
...
}
@objc private func signIn(_ target: UIButton) {
KindeSDKAPI.auth.login { result in
switch result {
case let .failure(error):
if !KindeSDKAPI.auth.isUserCancellationErrorCode(error) {
self.alert("Login failed: \(error.localizedDescription)")
}
case .success:
// Do something here
}
}
}
@objc private func register(_ target: UIButton) {
KindeSDKAPI.auth.register { result in
switch result {
case let .failure(error):
if !KindeSDKAPI.auth.isUserCancellationErrorCode(error) {
self.alert("Registration failed: \(error.localizedDescription)")
}
case .success:
// Do something here
}
}
}

Use custom auth pages

Link to this section

You can use a custom sign-up and sign-in page by passing the connectionId parameter to the login, register and createOrg methods.

KindeSDKAPI.auth.login(connectionId: CONNECTION_ID)
KindeSDKAPI.auth.register(connectionId: CONNECTION_ID)
KindeSDKAPI.auth.createOrg(connectionId: CONNECTION_ID)

See Custom sign-up and sign-in pages to learn more.

Bypass the Kinde initial login page

Link to this section

To skip the initial Kinde login page, pass the loginHint and connectionId parameters to the login and register methods.

KindeSDKAPI.auth.login(
connectionId: CONNECTION_ID,
loginHint: "alex@example.com"
)
KindeSDKAPI.auth.register(
connectionId: CONNECTION_ID,
loginHint: "phone:+61466043123:au"
)

This takes the user directly to the Kinde verification page, skipping the page where the user enters their identity, as the loginHint parameter prepopulates the user identity.

See Use custom sign-up and sign-in screens with Kinde for more information.

Handle redirect

Link to this section

Once your user is redirected back to your site from Kinde (it means you’ve logged in successfully), use the getToken method from KindeSDKAPI class to get a user token from Kinde.

Let’s look at an example of successful login.

KindeSDKAPI.auth.login { result in
switch result {
case let .failure(error):
if !KindeSDKAPI.auth.isUserCancellationErrorCode(error) {
self.alert("Login failed: \(error.localizedDescription)")
}
case .success:
self.onLoggedIn() // Calling this function
}
}
func onLoggedIn() {
self.isAuthenticated = true
self.getToken()
}
private func getToken() {
Task {
await asyncGetToken()
}
}
private func asyncGetToken() async -> String {
do {
let token = try await KindeSDKAPI.auth.getToken()
return token
} catch {
return "
}
}

This is implemented in much the same way as logging in or registering. The Kinde SPA client comes with a logout method.

@objc private func logout(_ target: UIButton) {
KindeSDKAPI.auth.logout { result in
if result {
// Do something
}
}
}

Get user information

Link to this section

To access the user information, use the getUserDetails helper function:

KindeSDKAPI.auth.getUserDetails()
// User(id: 1233, email: "dave@smith.com", given_name: "Dave", family_name: "Smith")

View users in Kinde

Link to this section

Navigate to the Users page within Kinde to see your newly registered user.

User Permissions

Link to this section

Once a user has been verified, your application will be returned the JWT token with an array of permissions for that user. You will need to configure your application to read permissions and unlock the respective functions.

You set Permissions in your Kinde account, the below is an example set of permissions.

let permissions = [
"create:todos",
"update:todos",
"read:todos",
"delete:todos",
"create:tasks",
"update:tasks",
"read:tasks",
"delete:tasks",
];

We provide helper functions to more easily access permissions:

KindeSDKAPI.auth.getPermission(name: "create:todos");
// Permission(organization: Organization(code: "org_1234"), isGranted: true)
KindeSDKAPI.auth.getPermissions();
// Permissions(organization: Organization(code: "org_1234"), permissions: ["create:todos", "update:todos", "read:todos"])

A practical example in code might look something like:

let isGranted = KindeSDKAPI.auth.getPermission(name: "create:todos")?.isGranted ?? false
if isGranted {
// show Create Todo button in UI
}

An audience is the intended recipient of an access token - for example the API for your application. The audience argument can be passed to the Kinde client to request an audience be added to the provided token.

The audience of a token is the intended recipient of the token.

{
"issuer": "https://<your-business>.kinde.com",
"clientId": "<your-client-id>",
"redirectUri": "<your-url-scheme>://kinde_callback",
"postLogoutRedirectUri": "<your-url-scheme>://kinde_logoutcallback",
"scope": "offline openid email profile",
"audience": "api.yourapp.com"
}

For details on how to connect, see Register an API

Overriding scope

Link to this section

By default the KindeSDK requests the following scopes:

  • profile
  • email
  • offline
  • openid

You can override this by passing scope into the KindeSDK

{
"issuer": "https://<your-business>.kinde.com",
"clientId": "<your-client-id>",
"redirectUri": "<your-url-scheme>://kinde_callback",
"postLogoutRedirectUri": "<your-url-scheme>://kinde_logoutcallback",
"scope": "offline openid email profile",
"audience": "api.yourapp.com"
}

Getting claims

Link to this section

We have provided a helper to grab any claim from your id or access tokens. The helper defaults to access tokens:

KindeSDKAPI.auth.getClaim(key: "aud");
// ["api.yourapp.com"]
KindeSDKAPI.auth.getClaim(key: "given_name", token: .idToken);
// "David

Create an organization

Link to this section

To create a new organization in your application, you will need to run a similar function to below:

@objc private func createOrg(_ target: UIButton) async {
do {
try await KindeSDKAPI.auth.createOrg(orgName: "Your Organization")
} catch {
...
}
}

Sign in and sign up to organizations

Link to this section

Kinde has a unique code for every organization. You’ll have to pass this code through when you register a new user.

Example function below:

KindeSDKAPI.auth.register(orgCode: "your_org_code");

If you want a user to sign in into a particular organization, pass this code along with the sign in method.

KindeSDKAPI.auth.login(orgCode: "your_org_code");

Following authentication, Kinde provides a json web token (jwt) to your application. Along with the standard information we also include the org_code and the permissions for that organization (this is important as a user can belong to multiple organizations and have different permissions for each).

Example of a returned token:

{
"aud": [],
"exp": 1658475930,
"iat": 1658472329,
"iss": "https://your_subdomain.kinde.com",
"jti": "123457890",
"org_code": "org_1234",
"permissions": ["read:todos", "create:todos"],
"scp": ["openid", "profile", "email", "offline"],
"sub": "kp:123457890"
}

The id_token will also contain an array of organizations that a user belongs to - this is useful if you wanted to build out an organization switcher for example.

{
...
"org_codes": ["org_1234", "org_4567"]
...
}

There are two helper functions you can use to extract information:

KindeSDKAPI.auth.getOrganization();
// Organization(code: "org_1234")
KindeSDKAPI.auth.getUserOrganizations();
// UserOrganizations(orgCodes: [Organization(code: "org_1234"), Organization(code: "org_abcd")])

For more information about how organizations work in Kinde, see Kinde organizations for developers.

The SDK can start the invitation sign-up flow when your app is opened via a URL containing an invitation_code query parameter.

For example, com.example.App://login?invitation_code=abc123 for an Application login URI of com.example.App://login and an invitation code of abc123.

To support the invitation sign-up flow in your iOS app, use one of the following methods:

To make the SDK automatically intercept your invitation code URLs, set KindeURLInterceptorEnabled to true in your app’s Info.plist.

Info.plist
<key>KindeURLInterceptorEnabled</key>
<true/>

The SDK then uses method swizzling to intercept incoming invitation URLs in your app delegate and scene delegate callbacks.

Delegate methods swizzled for URL interception

App delegate

  • application(_:open:options:)
  • application(_:continue:restorationHandler:)

Scene delegate

  • scene(_:willConnectTo:options:)
  • scene(_:openURLContexts:)
  • scene(_:continue:)

This is disabled by default and is only used when you set the KindeURLInterceptorEnabled flag to true.

We have provided a helper to return any features flag from the access token:

KindeSDKAPI.auth.getFlag(code: "theme")
// returns
Flag(code: "theme", type: Optional(KindeSDK.Flag.ValueType.string), value: black, isDefault: false)
KindeSDKAPI.auth.getFlag(code: "no-feature-flag")
// returns notFound
KindeSDKAPI.auth.getFlag(code: "no-feature-flag", defaultValue: "default-value")
// returns
Flag(code: "no-feature-flag", type: nil, value: "default-value", isDefault: true)
KindeSDKAPI.auth.getFlag(code: "no-feature-flag", defaultValue: "default-value", flagType: Flag.ValueType.bool)
// returns incorrectType("Flag \"theme\" is type string - requested type boolean")

We also require wrapper functions by type which should leverage getFlag above.

Get boolean flags

Link to this section
KindeSDKAPI.auth.getBooleanFlag(code: "is_dark_mode")
// true
KindeSDKAPI.auth.getBooleanFlag(code: "is_dark_mode", defaultValue: false)
// true
KindeSDKAPI.auth.getBooleanFlag(code: "new_feature")
// notFound
KindeSDKAPI.auth.getBooleanFlag(code: "new_feature", defaultValue: false)
// false
KindeSDKAPI.auth.getBooleanFlag(code: "theme")
// incorrectType("Flag \"theme\" is type string - requested type boolean")

Get string flags

Link to this section
KindeSDKAPI.auth.getStringFlag(code: "theme")
// pink
KindeSDKAPI.auth.getStringFlag(code: "theme", defaultValue: "black")
// pink
KindeSDKAPI.auth.getStringFlag(code: "cta_color")
// notFound
KindeSDKAPI.auth.getStringFlag(code: "cta_color", defaultValue: "blue")
// blue
KindeSDKAPI.auth.getStringFlag(code: "is_dark_mode")
// incorrectType("Flag \"is_dark_mode\" is type boolean - requested type string")

Get integer flags

Link to this section
KindeSDKAPI.auth.getIntegerFlag(code: "user_limit")
// 5
KindeSDKAPI.auth.getIntegerFlag(code: "user_limit", defaultValue: 3)
// 5
KindeSDKAPI.auth.getIntegerFlag(code: "team_count")
// notFound
KindeSDKAPI.auth.getIntegerFlag(code: "team_count", defaultValue: 4)
// 4
KindeSDKAPI.auth.getIntegerFlag(code: "is_dark_mode")
// incorrectType("Flag \"is_dark_mode\" is type boolean - requested type interger")

Once the user has successfully authenticated, you’ll have a JWT and a refresh token and that has been stored securely.

SDK API Reference

Link to this section

Either your Kinde URL or your custom domain. e.g https://yourapp.kinde.com.

Type: string

Required: Yes

The URL that the user will be returned to after authentication.

Type: string

Required: Yes

The unique ID of your application in Kinde.

Type: string

Required: Yes

postLogoutRedirectUri

Link to this section

Where your user will be redirected when they sign out.

Type: string

Required: No

The scopes to be requested from Kinde.

Type: string

Required: No

Default: openid profile email offline

The audience claim for the JWT.

Type: string

Required: No

KindeSDK methods

Link to this section

Constructs redirect url and sends user to Kinde to sign in.

Arguments:

orgCode?: String,
loginHint?: String,
connectionId?: String

Usage:

KindeSDKAPI.auth.login();
// or
KindeSDKAPI.auth.login(orgCode: “your organization code”)

Allow orgCode to be provided if a specific org is signed in to.

Constructs redirect url and sends user to Kinde to sign up.

Arguments:

orgCode?: String,
loginHint?: String,
planInterest?: String,
pricingTableKey?: String,
connectionId?: String

Usage:

KindeSDKAPI.auth.register();
// or
KindeSDKAPI.auth.register(orgCode: “your organization code”)

Allow orgCode to be provided if a specific org is registered to.

enablePrivateAuthSession

Link to this section

Call this method before login/register process to enable or disable message prompt.

Usage:

KindeSDKAPI.auth.enablePrivateAuthSession(true);

Logs the user out of Kinde.

Usage:

KindeSDKAPI.auth.logout();

Returns the raw token from URL after logged from Kinde.

Usage:

KindeSDKAPI.auth.getToken()

Sample output:

eyJhbGciOiJSUzI...

Constructs a redirect URL and sends the user to Kinde to sign up and create a new organization in your business.

Arguments:

orgName: String,
connectionId?: String

Usage:

KindeSDKAPI.auth.createOrg(orgName: "Your Organization");

Gets a claim from an access or ID token.

Arguments:

key: String, token: TokenType = .accessToken

Usage:

KindeSDKAPI.auth.getClaim(key: ”given_name”, token: .idToken);

Sample output: "David"

Returns the state of a given permission.

Arguments:

name: String

Usage:

KindeSDKAPI.auth.getPermission(name: ”read:todos”);

Sample output:

Permissions
(organization: Organization(code: "org_1234"), isGranted: true)

getPermissions

Link to this section

Returns all permissions for the current user for the organization they are signed into.

Usage:

KindeSDKAPI.auth.getPermissions();

Sample output:

Permissions
(organization: Organization(code: "org_1234"),
permissions: ["create:todos", "update:todos", "read:todos"])

getOrganization

Link to this section

Get details for the organization your user is signed into.

Usage:

KindeSDKAPI.auth.getOrganization();

Sample output:

Organization(code: "org_1234")

getUserOrganizations

Link to this section

Gets an array of all organizations the user has access to.

Usage:

KindeSDKAPI.auth.getUserOrganizations();

Sample output:

UserOrganizations
(orgCodes: [Organization(code: "org_1234"), Organization(code: "org_abcd")])

getUserDetails

Link to this section

Get details for the organization your user is signed into.

Usage:

KindeSDKAPI.auth.getOrganization();

Sample output:

User
(id: 1233,
email: "dave@smith.com",
given_name: "Dave",
family_name: "Smith")

isAuthenticated

Link to this section

Return the boolean to demonstrate whether the user is authenticated or not.

Usage:

KindeSDKAPI.auth.isAuthenticated()

Sample output: true or false

Get a flag from the feature_flags claim of the access_token

Arguments:

code: String
defaultValue?: Any
flagType?: Flag.ValueType

Usage:

KindeSDKAPI.auth.getFlag(code: "theme")

Sample output:

Flag(code: "theme", type: Optional(KindeSDK.Flag.ValueType.string), value: black, isDefault: false)

getBooleanFlag

Link to this section

Get a boolean flag from the feature_flags claim of the access token

Arguments:

code: String
defaultValue?: String

Usage:

KindeSDKAPI.auth.getBooleanFlag(code: "is_dark_mode")

Sample output: true

Get a string flag from the feature_flags claim of the access token

Arguments:

code: String
defaultValue?: String

Usage:

KindeSDKAPI.auth.getStringFlag(code: "theme")

Sample output: pink

getIntegerFlag

Link to this section

Get a integer flag from the feature_flags claim of the access token

Arguments:

code: String
defaultValue?: String

Usage:

KindeSDKAPI.auth.getIntegerFlag(code: "user_limit")

Sample output: 5

If you need help connecting to Kinde, contact us at support@kinde.com.