• Stars
    star
    559
  • Rank 79,650 (Top 2 %)
  • Language
    Swift
  • License
    Apache License 2.0
  • Created over 6 years ago
  • Updated 3 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

JSON Web Tokens in Swift

Kitura

APIDoc Build Status - Master macOS Linux Apache 2 Slack Status

SwiftJWT

An implementation of JSON Web Token using Swift. JWTs offer a lightweight and compact format for transmitting information between parties, and the information can be verified and trusted due to JWTs being digitally signed.

For more information on JSON Web Tokens, their use cases and how they work, we recommend visiting jwt.io.

Reminder: JWTs sent as JWS do not encrypt data, so never send anything sensitive or confidential in a JWT. This library does not currently support JWE.

Swift version

The latest version of Swift-JWT requires Swift 5.2 or later. You can download this version of the Swift binaries by following this link. Compatibility with other Swift versions is not guaranteed.

Usage

Swift Package Manager

Add dependencies

Add the Swift-JWT package to the dependencies within your applicationโ€™s Package.swift file. Substitute "x.x.x" with the latest Swift-JWT release.

.package(url: "https://github.com/Kitura/Swift-JWT.git", from: "x.x.x")

Add SwiftJWT to your target's dependencies:

.target(name: "example", dependencies: ["SwiftJWT"]),

Import package

import SwiftJWT

Cocoapods

To include Swift-JWT in a project using CocoaPods, add SwiftJWT to your Podfile:

pod 'SwiftJWT'

Getting Started

The JWT model

In its compact form, a JSON Web Tokens consist of three sections of Base64Url encoded JSON, separated by dots (.).
These section are: Headers, Claims and the Signature. Therefore, a JWT typically looks like the following: xxxxx.yyyyy.zzzzz

Header

The Header struct contains the fields of the JSON Web Token header as defined by RFC7515.
The "typ" header will default to "JWT". The "alg" header will be set to the algorithm name when you sign the JWT.
The other Header fields can be set when initializing the Header or by changing them directly on the Header object.

let myHeader = Header(kid: "KeyID1")

Claims

Claims are statements about an entity (typically, the user) and additional data. The Claims are defined by creating a Swift type that conforms to the Claims protocol. The fields of this type represent the information that will be shared using the JWT.

A list of recommended claims is defined in RFC7519.

struct MyClaims: Claims {
    let iss: String
    let sub: String
    let exp: Date
    let admin: Bool
}
let myClaims = MyClaims(iss: "Kitura", sub: "John", exp: Date(timeIntervalSinceNow: 3600), admin: true)
ClaimsExamples

This library includes some example Claims structs as defined by their online specifications:

  • ClaimsStandardJWT as defined in RFC7519.
  • ClaimsMicroProfile as defined here.
  • ClaimsOpenID.swift as defined here.

JWT

The JWT struct represents the Header and Claims of a JSON Web Token.
You can initialize a JWT by decoding a JWT String, or by providing the JWT Header and Claims.

let myJWT = JWT(header: myHeader, claims: myClaims)

Signing and Verifying JSON web tokens

Creating public and private keys

To sign and verify a JWT using an RSA algorithm, you must provide a public and private key. This could be the contents of a .key file generated via the following Terminal commands:

$ ssh-keygen -t rsa -b 4096 -m PEM -f privateKey.key
# Don't add a passphrase
$ openssl rsa -in privateKey.key -pubout -outform PEM -out privateKey.key.pub

This will create a public and private key pair on your system, and the contents of the private key can be passed into a Swift variable using the following code:

let privateKeyPath = URL(fileURLWithPath: getAbsolutePath(relativePath: "/path/to/privateKey.key"))
let privateKey: Data = try Data(contentsOf: privateKeyPath, options: .alwaysMapped)
let publicKeyPath = URL(fileURLWithPath: getAbsolutePath(relativePath: "/path/to/publicKey.key"))
let publicKey: Data = try Data(contentsOf: publicKeyPath, options: .alwaysMapped)

For details on creating elliptic curve public and private keys, view the BlueECC README.txt.

Sign a JWT using a JWTSigner

The struct JWTSigner contains the algorithms that can be used to sign a JWT.

Initialize a JWTSigner using the static function corresponding to the desired RSA algorithm:

let jwtSigner = JWTSigner.rs256(privateKey: privateKey)

To generate a signed JWT string, call the sign function on your JWT instance, passing in a JWTSigner:

let signedJWT = try myJWT.sign(using: jwtSigner)

The resulting signedJWT will be a String of the form:

<encoded header>.<encoded claims>.<signature>

Note: The sign function sets the alg (algorithm) field of the header.

Verify a JWT using JWTVerifier

The struct JWTVerifier contains the algorithms that can be used to verify a JWT.

Initialize a JWTVerifier using the static function corresponding to the desired RSA algorithm:

let jwtVerifier = JWTVerifier.rs256(publicKey: publicKey)

To verify a signed JWT string, call the static verify function, passing in your JWT string and the JWTVerifier:

let verified = JWT<MyClaims>.verify(signedJWT, using: jwtVerifier)

The verified field will be a bool that is true if the signature is verified.

Supported Algorithms

The supported algorithms for signing and verifying JWTs are:

  • RS256 - RSASSA-PKCS1-v1_5 using SHA-256
  • RS384 - RSASSA-PKCS1-v1_5 using SHA-384
  • RS512 - RSASSA-PKCS1-v1_5 using SHA-512
  • HS256 - HMAC using using SHA-256
  • HS384 - HMAC using using SHA-384
  • HS512 - HMAC using using SHA-512
  • ES256 - ECDSA using using SHA-256 and a P-256 curve
  • ES384 - ECDSA using using SHA-384 and a P-384 curve
  • ES512 - ECDSA using using SHA-512 and a P-521 curve
  • PS256 - RSA-PSS using SHA-256
  • PS384 - RSA-PSS using SHA-384
  • PS512 - RSA-PSS using SHA-512
  • none - Don't sign or verify the JWT

Note: ECDSA and RSA-PSS algorithms require a minimum Swift version of 4.1.

Validate claims

The validateClaims function validates the standard Date claims of a JWT instance. The following claims are validated if they are present in the Claims object:

  • exp (expiration date)
  • nbf (not before date)
  • iat (issued at date)

The method returns ValidateClaimsResult - an struct that list the various reasons for validation failure. If the validation succeeds ValidateClaimsResult.success is returned. The leeway parameter is the TimeInterval in seconds that a standard Date claim will be valid outside of the specified time. This can be used to account for clock skew between issuers and verifiers.

let validationResult = verified.validateClaims(leeway: 10)
if validationResult != .success {
    print("Claims validation failed: ", validationResult)
}

Decode a JWT from a JWT string

A JWT struct can be initialized from a JWT string. If a JWTVerifier is provided it will be used to verify the signature before initialization

let newJWT = try JWT<MyClaims>(jwtString: signedJWT, verifier: jwtVerifier)

JWTEncoder and JWTDecoder

The JWTEncoder and JWTDecoder classes encode and decode JWT Strings using the same API as JSONEncoder and JSONDecoder:

 let jwtEncoder = JWTEncoder(jwtSigner: jwtSigner)
 let jwtString = try jwtEncoder.encodeToString(myJWT)

 let jwtDecoder = JWTDecoder(jwtVerifier: jwtVerifier)
 let jwt = try jwtDecoder.decode(JWT<MyClaims>.self, fromString: jwtString)

Because JWTEncoder and JWTDecoder conform to KituraContract's BodyEncoder and BodyDecoder protocols, they can be used as a custom coder in Codable routes for sending and receiving JWTs:

 router.encoders[MediaType(type: .application, subType: "jwt")] = { return jwtEncoder }
 router.decoders[MediaType(type: .application, subType: "jwt")] = { return jwtDecoder }

This allows for the use of JWT's in information exchange. By sending and receiving JWT's you can ensure the sending is who they say they are and verify the content hasn't been tampered with.

API Documentation

For more information visit our API reference.

Community

We love to talk server-side Swift, and Kitura. Join our Slack to meet the team!

License

This library is licensed under Apache 2.0. Full license text is available in LICENSE.

More Repositories

1

Kitura

A Swift web framework and HTTP server.
Swift
7,628
star
2

BlueSocket

Socket framework for Swift using the Swift Package Manager. Works on iOS, macOS, and Linux.
Swift
1,407
star
3

Swift-Kuery

SQL database abstraction layer
Swift
426
star
4

Swift-SMTP

Swift SMTP client
Swift
261
star
5

Swift-Kuery-ORM

An ORM for Swift, built on Codable
Swift
212
star
6

BlueCryptor

Swift cross-platform crypto library using CommonCrypto/libcrypto
Swift
191
star
7

HeliumLogger

A lightweight logging framework for Swift
Swift
176
star
8

swift-html-entities

HTML5 spec-compliant character encoder/decoder for Swift
Swift
170
star
9

swift-ubuntu-docker

๐Ÿšซ This repo is deprecated - please use the images here: https://hub.docker.com/_/swift
Vim Script
154
star
10

BlueRSA

RSA public/private key encryption, private key signing and public key verification in Swift using the Swift Package Manager. Works on iOS, macOS, and Linux (work in progress).
Swift
132
star
11

SwiftyRequest

SwiftyRequest is an HTTP networking library built for Swift.
Swift
110
star
12

Kitura-net

Kitura networking
Swift
104
star
13

BlueSSLService

SSL/TLS Add-in for BlueSocket using Secure Transport and OpenSSL
Swift
97
star
14

Kitura-redis

Swift Redis library
Swift
95
star
15

BlueECC

Elliptic-curve cryptography for Swift
Swift
94
star
16

BlueSignals

Generic Cross Platform Signal Handler
Swift
94
star
17

Configuration

Hierarchical configuration manager for Swift applications
Swift
81
star
18

Kitura-Sample

A sample application that shows how to use various features of Kitura
Swift
81
star
19

Kitura-WebSocket

WebSocket support for Kitura
Swift
68
star
20

OpenSSL

Swift modulemaps for libSSL and libcrypto
C
61
star
21

Swift-Kuery-PostgreSQL

PostgreSQL plugin for Swift-Kuery framework
Swift
61
star
22

SwiftKafka

Swift SDK for Apache Kafka
Swift
60
star
23

KituraKit

Swift client library for using Codable routes with Kitura
Swift
59
star
24

Kitura-CouchDB

CouchDB adapter for Kitura
Swift
51
star
25

CircuitBreaker

A Swift Circuit Breaker library โ€“ Improves application stability and reliability.
Swift
47
star
26

Kitura-Credentials

A pluggable framework for validating user credentials in a Swift server using Kitura
Swift
41
star
27

Kitura-NIO

A networking library for Kitura, based on SwiftNIO
Swift
38
star
28

Kitura-OpenAPI

OpenAPI support for Kitura
Swift
37
star
29

TypeDecoder

A Swift library to allow the runtime inspection of Swift language native and complex types.
Swift
37
star
30

SwiftKueryMySQL

MySQL plugin for Swift-Kuery framework
Swift
35
star
31

Package-Builder

Build and utility scripts used for continuous integration builds for Swift Package Manager projects on the Travis CI environment
Shell
35
star
32

CCurl

Modulemap for the libcurl library
Objective-C
31
star
33

Kitura-StencilTemplateEngine

Stencil templating for Kitura
Swift
27
star
34

Kitura-Markdown

Templating engine for Kitura that uses Markdown based templates
C
26
star
35

LoggerAPI

Logger protocol
Swift
26
star
36

kitura.dev

http://www.kitura.dev
JavaScript
26
star
37

Health

An application health library for Swift.
Swift
22
star
38

Kitura-Session

A pluggable framework for managing user sessions in a Swift server using Kitura
Swift
19
star
39

Kitura-WebSocket-NIO

A SwiftNIO based implementation of WebSocket for Kitura
Swift
18
star
40

CommonCrypto

CommonCrypto Module Map
Swift
18
star
41

FileKit

Swift
17
star
42

Kitura-TemplateEngine

Kitura Template Engine protocol
Swift
16
star
43

Swift-Kuery-SQLite

An SQLite plugin for the Swift-Kuery framework
Swift
16
star
44

Kitura-CredentialsHTTP

A plugin for the Kitura-Credentials framework that authenticates using HTTP Basic and Digest authentication
Swift
16
star
45

kitura-cli

โŒจ๏ธ Kitura command-line interface
Go
14
star
46

KituraContracts

A library containing type definitions shared by client and server Kitura code.
Swift
13
star
47

CZlib

Module map for Zlib library
Swift
12
star
48

CloudEnvironment

Convenience Swift package for accessing environment variables, credentials.
Swift
12
star
49

Kitura-CredentialsFacebook

A plugin for the Kitura-Credentials framework that authenticates using the Facebook web login
Swift
10
star
50

Kitura-CORS

Kitura CORS middleware
Swift
10
star
51

Kitura-Cache

Kitura cache
Swift
10
star
52

Kitura-CredentialsGoogle

A plugin for the Kitura-Credentials framework that authenticates using the Google web login
Swift
9
star
53

Swift-cfenv

Easy access to Cloud Foundry application environment for Swift Packages.
Swift
9
star
54

Kitura-Compression

Kitura compression middleware
Swift
7
star
55

CEpoll

A modulemap file and include to help Swift code use epoll on Linux
Swift
6
star
56

Kitura-WebSocket-Client

A WebSocket client based on SwiftNIO
Swift
6
star
57

Kitura-CredentialsGitHub

A plugin for the Kitura-Credentials framework that authenticates using the GitHub web login
Swift
6
star
58

Kitura-MustacheTemplateEngine

Adapter of GRMustache Template Engine to Kitura Template Engine
Swift
5
star
59

CHTTPParser

Modulemap for the http-parser library
C
5
star
60

Kitura-WebSocket-Compression

A WebSocket compression library based on SwiftNIO
Swift
4
star
61

generator-swiftserver-projects

Autogenerated Kitura projects
Shell
4
star
62

Kitura-Session-Redis

Kitura-Session store using Redis as the backing store
Swift
4
star
63

Kitura-Benchmarks

Benchmarks for Kitura
Swift
3
star
64

homebrew-kitura

Homebrew tap
Ruby
3
star
65

Kitura-CredentialsJWT

A plugin for the Kitura-Credentials framework that supports JWT authentication.
Swift
3
star
66

ShellToolKit

Utility classes to help with common system/shell actions in Swift
Swift
3
star
67

anapistula

Simple standalone web server in swift
Swift
2
star
68

CLibpq

PostgreSQL wrapper
Swift
2
star
69

CMySQL

Swift
1
star
70

Kitura-CI

Repository to hold the testing scripts for some Kitura repositories
Shell
1
star
71

Maintainers

Files relevant to Kitura project maintainers
Swift
1
star
72

StarterWebServer

A starter web server that can be used as a template for a new project
Swift
1
star