Skip to content

okta/okta-sdk-swift

Repository files navigation

Build Status Beta Release License Support

Okta Swift Management SDK

This repository contains the Okta management SDK for Swift. This SDK can be used in your server-side code to interact with the Okta management API and:

Requires Swift version 5.5 or higher.

You can also learn more on the Okta + Swift page in our documentation.

WARNING: This SDK is not intended for use within production applications, or applications deployed to untrusted devices (e.g. via the app store or private distribution). Embedding SSWS tokens within applications is unsafe, and is not recommended.

Release status

This library uses semantic versioning and follows Okta's Library Version Policy.

Version Status
0.x ⚠️ Beta Release

The latest release can always be found on the releases page.

Need help?

Note: This SDK is in beta status, and is currently unsupported. At this time, there are no plans for this to become supported, and will remain in beta status. If you run into problems using the SDK, you can:

Getting started

To get started, you will need:

  • An Okta account, called an organization (sign up for a free developer organization if you need one).
  • An API token.
  • Xcode targeting iOS 15 or above, tvOS 15 or above, or macOS 12 or above.

Swift Package Manager

Add the following to the dependencies attribute defined in your Package.swift file. You can select the version using the majorVersion and minor parameters. For example:

dependencies: [
    .Package(url: "https://github.com/okta/okta-sdk-swift.git", majorVersion: <majorVersion>, minor: <minor>)
]

Initializing a client

Construct a client instance by passing it your Okta domain name and API token:

import OktaSdk

let config = OktaClient.Configuration(apiKey: "{API_TOKEN}", domain: "{{yourOktaDomain}}")
let client = OktaClient(configuration: config)

Once you initialize a client, you can call methods to make requests to the Okta API.

Making API calls

The client provides async methods using Swift Concurrency for each API call.

Most methods are grouped by the API endpoint they belong to. For example, methods that call the Users API are organized under the User resource client client.user.*.

Response Objects

All results, regardless of the function type, will return an instance of OktaResponse<T>, whose embedded type is generic. This response object contains information related to the response, such as rate limit information, pagination links, and the requestId returned from the server.

let response = try await client.user.listUsers()

// Use the response

Usage guide

These examples will help you understand how to use this library.

import OktaSdk

func getUsers() async {
    for user in try await client.user.listUsers().result {
        print(user.id)
    }
}

Authenticate a User

This library should only be used with the Okta management API.

Assume the client is instantiated before each example below. The following samples will use the Swift Concurrency variant functions for brevity.

import OktaSdk
let client = OktaClient(configuration: .init(apiKey: "API_TOKEN", domain: "test.okta.com"))

Get a User

let user = try await client.user.getUser(userId: "USER_ID").result

List all Users

let users = try await client.user.listUsers().result

Filter or search for Users

// Query parameters are optional on methods that can use them!
// Check the method definition for details on which query parameters are accepted.
let users = try await client.listUsers(filter: "status eq \"ACTIVE\"").result

Create a User

// Create Password
let password = PasswordCredential(value: "Password123")

// Create User Credentials
let userCreds = UserCredentials(password: password)

// Create User Profile and CreateUser Request
let userProfile = UserProfile()
userProfile.firstName = "John"
userProfile.lastName = "Doe"
userProfile.email = "John.Doe"
userProfile.login = "John.Doe"

let createUserReq = CreateUserRequest(credentials: userCreds,
                                      profile: userProfile)

// Create User
let user = try await client.user.createUser(createUserRequest: createUserReq).result

Update a User

// Assume user object saved to variable `user`
user.profile.nickName = "Oktanaut"

// Update User with new details
let result = try await client.user.updateUser(userId: user.id, user: user)

Remove a User

You must first deactivate the user, and then you can delete the user.

// Assuming user starts off with a status of 'ACTIVE'

// Deactivate
try await client.user.deactivateOrDeleteUser(userId: user.id)

// Then delete
try await client.user.deactivateOrDeleteUser(userId: user.id)

List a User's Groups

let result = try await client.listUserGroups(userId: user.id)

Create a Group

// Create Group Model
let profile = GroupProfile(name: "Group-Test")

let groupModel = Group(profile: profile)

// Create Group
let result = try await client.group.createGroup(group: groupModel)

Add a User to a Group

let result = try await client.group.addUserToGroup(groupId: group.id, userId: user.id)

List a User's enrolled Factors

let result = try await client.userFactor.listSupportedFactors(userId: user.id)

Pagination

If your request comes back with more than the default, you can request the next page.

Example of listing users 1 at a time:

var response = try await client.users.listUsers(limit: 1)
var users = response.result

// Check if there more pages follow
while result.links.next != nil {
    response = try await client.fetch(.next, from: response)

    users.append(contentsOf: response.result)
}

Rate Limiting

The Okta API will return 429 responses if too many requests are made within a given time. Please see Rate Limiting at Okta for a complete list of which endpoints are rate limited. When a 429 error is received, the OktaResponse.rateInfo.reset value will tell you the time at which you can retry.

Contributing

We're happy to accept contributions and PRs! Please see the Contribution Guide to understand how to structure a contribution.

Updating to the new spec

Generating a new version of the SDK using an updated spec can be done as follows:

docker run --rm -v $PWD:/local \
    openapitools/openapi-generator-cli generate  \
    --api-package OktaSdk \
    --generator-name swift5 \
    --git-host github.com \
    --git-repo-id okta-sdk-swift \
    --git-user-id okta \
    --config /local/openapi-config.yaml \
    --input-spec /local/management-codegen.yaml \
    --template-dir /local/openapi-template \
    --output /local