Swiftpack.co -  okta/okta-ios-jwt as Swift Package
Swiftpack.co is a collection of thousands of indexed Swift packages. Search packages.
okta/okta-ios-jwt
okta-ios-jwt
.package(url: "https://github.com/okta/okta-ios-jwt.git", from: "2.3.3")

OktaJWT

Version CI Status License Platform Carthage compatible Platform

Overview

This library handles decoding and validating a JSON Web Token (JWT) issued by an Okta authorization server. It provides an easy-to-use and customizable interface for ID Token validation based on OIDC 3.1.3.7 for iOS applications.

Installation

Cocoapods

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

pod 'OktaJWT'

Swift Package Manager

To add a package dependency to your Xcode project using Swift Package Manager, select in Xcode File > Swift Packages > Add Package Dependency and enter the repository URL:

https://github.com/okta/okta-ios-jwt.git

Carthage

To integrate this SDK into your Xcode project using Carthage, specify it in your Cartfile:

github "okta/okta-ios-jwt"

Usage

This library supports validating JWTs by extending the JSONWebToken Swift library. By default, it will fetch the public keys from the OAuth 2.0 /keys endpoint of the specified authorization server, validate the JWT signature, and verify the token against given assertions.

First, create a dictionary of verification options and instantiate the OktaJWTValidator:

let options = [
  "issuer": "https://{yourOktaDomain}.com/oauth2/default,
  "audience": "{aud}", // More info below
  ...
] as [String: Any]

let validator = OktaJWTValidator(options)

Finally, check to see if the JWT is valid:

let jwtString = "ey...."

do {
  let valid = try validator.isValid(jwtString)
  print("Valid: \(valid)")
} catch let error {
  print("Error: \(error)")
}

idToken Validation

When using OpenID Connect as an authentication mechinism, it is important to verify the idToken returned from the /token endpoint. To ensure the token is valid, include the following in your verification options:

To learn more about the verification cases and Okta's tokens, take a look at Working with OAuth 2.0 Tokens.

let options = [
  "issuer": "https://{yourOktaDomain}.com/oauth2/default",
  "audience": "0abc123..",
  "exp": true,
  "iat": true,
  "leeway": 3000, // allow ~5 minutes for clock drift (exp and iat),
  "nonce": "1a2b3c4d..."
] as [String: Any]

let validator = OktaJWTValidator(options)

let idToken = "ey..."

do {
  let valid = try validator.isValid(idToken)
  print("Valid: \(valid)")
} catch let error {
  // Misc Error: {error}
}

To ensure proper error handling, you can catch, handle, and recover from specific errors:

do {
  let valid = try validator.isValid(idToken)
  print("Valid: \(valid)")
} catch OktaJWTVerificationError.malformedJWT {
  // Malformed idToken -> "ey.xx"
} catch OktaJWTVerificationError.nonSupportedAlg(let algType) {
  // Algorithm type {algType} not supported
} catch OktaJWTVerificationError.invalidIssuer {
  // idToken issuer != given issuer
} catch OktaJWTVerificationError.invalidAudience {
  // idToken audience != given audience
} catch OktaJWTVerificationError.invalidSignature {
  // Invalid signature
} catch OktaJWTVerificationError.expiredJWT {
  // idToken expired!
} catch OktaJWTVerificationError.issuedInFuture {
  // idToken issued in the future
} catch OktaJWTVerificationError.invalidNonce {
  // Invalid nonce
} catch let error {
  // Misc Error: {error}
}

Custom Claim Validation

You can ask the verifier to assert a custom set of claims, provided that it can be validated as a String.

let options = [
  "issuer": "https://{yourOktaDomain}.com/oauth2/default",
  "audience": "0abc123..",
  "exp": true,
  "iat": true,
  "preferred_username": "username"
] as [String: Any]

let validator = OktaJWTValidator(options)

let jwtString = "ey..."

do {
  let valid = try validator.isValid(jwtString)
  print("Valid: \(valid)")
} catch OktaJWTVerificationError.invalidClaim(let claim) {
  // Claim {claim} not present
} catch let error {
  // Misc Error: {error}
}

Advanced Options

Optional Validator Params

  • jwk: Pass a JSON Web Key (JWK) to be used over the ones provided by the /keys endpoint.
  • RSAKey: Use an existing RSAKey
let options = [
  "issuer": "https://{yourOktaDomain}.com/oauth2/default",
  "audience": "0abc123..",
  ...
] as [String: Any]

let jwtString = "ey..."


// Use custom JWK
let givenJWK = [
  "alg": "RS256",
  "e": "AQAB",
  "n": "kR7T4d_6RrTLQ4rdhdexVsGs6D0UwY9gZotmC7BEMvFovvnB0U3fy7WpmUn3aL9ooUJuDj19h17l3" +
       "gENKTaZOLucmLVq6HlK8coukxzk8_zhllrWXXFVwB3TlB-zR2EfWi_FKnyHHrSQ0lb1RfO7wberhy" +
       "_FK6n6WA5lCMYVfOGVm3aV6vfAojS7y1QzyimytitCRsOnIW7QmlZ1ZtKcEKb0pGdwSAAj-OSldZL" +
       "uLBj9B_t6HMq0xPVNhWgtYGDFNARaCIcvuP236VpGsw3EH4zfeKVMpScHC2j3y5JvMefn_iVgBzW7" +
       "9qs6QPbC6Y1_yCJv-ZRfur3Tk92Hq82B4w",
  "kid": "someKeyId",
  "kty": "RSA",
  "use": "sig"
] as [String: Any]

let validator = OktaJWTValidator(options, jwk: givenJWK)

do {
  let valid = try validator.isValid(jwtString)
  print("Valid: \(valid)")
} catch let error {
  // Misc Error: {error}
}

//  -- OR --

// Use existing RSAKey
let rsaKey = RSAKey.registeredKeyWithTag("myKeyTag")

let validator = OktaJWTValidator(options, key: rsaKey)

do {
  let valid = try validator.isValid(jwtString)
  print("Valid: \(valid)")
} catch let error {
  // Misc Error: {error}
}

Contributing

We are happy to accept contributions and PRs! Please see the contribution guide to understand how to structure a contribution.

GitHub

link
Stars: 12
Last commit: 3 weeks ago

Ad: Job Offers

iOS Software Engineer @ Perry Street Software
Perry Street Software is Jack’d and SCRUFF. We are two of the world’s largest gay, bi, trans and queer social dating apps on iOS and Android. Our brands reach more than 20 million members worldwide so members can connect, meet and express themselves on a platform that prioritizes privacy and security. We invest heavily into SwiftUI and using Swift Packages to modularize the codebase.

Release Notes

2.3.3
13 weeks ago
  • #46 - Swift Package Manager
  • #44 - RS384 and RS512

Swiftpack is being maintained by Petr Pavlik | @ptrpavlik | @swiftpackco | API