iOS SDK

Integrate Kinde authentication with your iOS app. Simply configure, register, log in, and log out, and the authentication state is securely stored on the iOS keychain across app restarts.

These instructions assume you already have a Kinde account. You can register for free here (no credit card required).

Install

KindeSDK is available through CocoaPods. To install it, simply 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.

Configure Kinde

Callback URLs

On the Kinde web app navigate to Settings -> App keys and find the Callbacks input field.

Here you want to put in the callback URLs for your iOS app, which should look something like this:

  1. In Kinde, go to Settings > Applications.
  2. View the application details. This is where you get app keys and set the callback URLs.
  3. Add your callback URLs in the relevant fields. For example:
    • Allowed callback URLs: {your_url_scheme}://kinde_callback
    • Allowed logout redirect URLs: {your_url_scheme}://kinde_logoutcallback
  4. Select Save.

Note: your_url_scheme can be any valid custom URL scheme, such as your app’s bundle ID or an abbreviation. It must match the scheme component of the Allowed callback URLs and Allowed logout redirect URLs you configure in your App Keys page for your Kinde business.

Environments

If you would like to use our Environments feature as part of your development process. You will need to create them first within your Kinde account. In this case you would use the Environment subdomain in the code block above.

Configuring your app

Environment variables

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

You can find these variables on your Kinde Settings > App keys page.

  • issuer: your Kinde domain
  • redirectUri: After the user authenticates we will callback to this address. Make sure this URL is under your allowed callback URLs.
  • postLogoutRedirectUri: where you want users to be redirected to after logging out. Make sure this URL is under your allowed logout redirect URLs.
  • clientId - you can find this on the App Keys page
{
    "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"
}

Example:

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

Integrate with your app

Before Auth can be used, a call to Auth.configure() must be made, typically in AppDelegate as part of application(launchOptions) for a UIKit app, or the @main initialization logic for a SwiftUI app. Likewise, if the Kinde Management API client is used, KindeManagementApiClient.configure() must be called prior to use. AppDelegate.swift:

...
import KindeSDK
...

class AppDelegate: UIResponder, UIApplicationDelegate {
	...
	func application(...) {
		...
		// The Kinde authentication service must be configured before use
		Auth.configure(logger: Logger())
		// If the Kinde Management API is required, it must be configured before use
		KindeManagementApiClient.configure()
		...
	}
	...
}

Login / Register

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

As an example if you 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) {
	Auth.login(viewController: self) { result in
		switch result {
			case let .failure(error):
				if (!Auth.isUserCancellationErrorCode(error)) {
					self.alert("Login failed: \(error.localizedDescription)")
				}
			case .success:
				// Do something here
		}
	}
}

@objc private func register(_ target: UIButton) {
	Auth.register(viewController: self) { result in
		switch result {
			case let .failure(error):
				if (!Auth.isUserCancellationErrorCode(error)) {
					self.alert("Registration failed: \(error.localizedDescription)")
				}
			case .success:
				// Do something here
		}
	}
}

Handle redirect

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

Let’s look at an example of successful login.

Auth.login(viewController: self) { result in
	switch result {
		case let .failure(error):
			if (!Auth.isUserCancellationErrorCode(error)) {
				self.alert("Login failed: \(error.localizedDescription)")
			}
		case .success:
			self.makeAuthenticatedRequest() // Calling this function
		}
}

@objc private func makeAuthenticatedRequest() {
	Auth.performWithFreshTokens { tokens in
		switch tokens {
			case let .failure(error):
				print("Failed to get auth token: \(error.localizedDescription)")
			case let .success(tokens):
				let accessToken = tokens.accessToken
				print("Calling API with accessToken: \(accessToken)")
		}
	}
}

Logout

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) {
	Auth.logout(viewController: self) { result in
		if result {
			// Do something
		}
	}
}

Get user information

To access the user information, use the getUser method of OAuthAPI class.

OAuthAPI.getUser { (userProfile, error) in
    if let userProfile = userProfile {
        let userName = "\(userProfile.firstName ?? "") \(userProfile.lastName ?? "")"
        print("Got profile for user \(userName)")
    }
    if let error = error {
        // Need to implement
    }
}

View users in Kinde

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

User Permissions

Once a user has been verified, your product/application will be returned the JWT token with an array of permissions for that user. You will need to configure your product/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",
];

If you need any assistance with getting Kinde connected, reach out to us at support@kinde.com.

Talk to us

If you can’t find what you’re looking for in our help center — email our team

Contact us
Talk to us