Decoding JSON Web Tokens in Swift

jwt swift 4
swift-jwt decode
generate jwt token swift
swift-jwt tutorial
jwt decode online
jwt - java
jwt claims

trying to decode a JWT payload in Swift and having a really difficult time

static func decodePayload(tokenstr: String) {

    //splitting JWT to extract payload
    let arr = split(tokenstr) {$0 == "."}

    //base64 encoded string i want to decode
    let base64String = arr[1] as String
    println(base64String) //eyJleHAiOjE0MjY4MjIxNjMsImlkIjoiNTUwYjA3NzM4ODk1NjAwZTk5MDAwMDAxIn0

    //attempting to convert base64 string to nsdata 
    let nsdata: NSData = NSData(base64EncodedString: base64String, options: NSDataBase64DecodingOptions(rawValue: 0))

    //decoding fails because nsdata unwraps as nil
    let base64Decoded: NSString = NSString(data: nsdata!, encoding: NSUTF8StringEncoding)!


is not a valid Base64 encoded string because its length is not a multiple of 4. Some Base64 decoder tolerate this error, but the NSData methods don't.

So this is actually an error on the server side creating the Base64 encoded string. If necessary, you can fix it in your app by adding the required padding with = characters (code updated for Swift 2):

var base64String = arr[1] as String
if base64String.characters.count % 4 != 0 {
    let padlen = 4 - base64String.characters.count % 4
    base64String += String(count: padlen, repeatedValue: Character("="))

And now the decoding works as expected:

if let data = NSData(base64EncodedString: base64String, options: []),
    let str = String(data: data, encoding: NSUTF8StringEncoding) {
    print(str) // {"exp":1426822163,"id":"550b07738895600e99000001"}

Swift 4:

var base64String = "eyJleHAiOjE0MjY4MjIxNjMsImlkIjoiNTUwYjA3NzM4ODk1NjAwZTk5MDAwMDAxIn0"

if base64String.count % 4 != 0 {
    let padlen = 4 - base64String.count % 4
    base64String.append(contentsOf: repeatElement("=", count: padlen))

if let data = Data(base64Encoded: base64String) ,
    let str = String(data: data, encoding: .utf8) {
    print(str) // {"exp":1426822163,"id":"550b07738895600e99000001"}

auth0/JWTDecode.swift: A library to help you decode JWTs , Support for generating signed Json Web Tokens to call your APIs and flow the user identity securely. Analytics of how, when and where users are logging in. Pull  How can I decode JWT (JSON web token) token in Swift? Ask Question Asked 3 years, 4 months ago. Active 9 months ago. Viewed 13k times 12. 5. I have a JWT token like

Above solution is working for me, I converted into swift3

Here you can find swift3 code

var base64Str = arr[1] as String
if base64Str.characters.count % 4 != 0 {
    let padlen = 4 - base64Str.characters.count % 4      
    base64Str += String(repeating: "=", count: padlen)

if let data = Data(base64Encoded: base64Str, options: []),
    let str = String(data: data, encoding: String.Encoding.utf8) {

How can I decode JWT (JSON web token) token in Swift?, If you are okay with using a library i would suggest this​JWTDecode.swift. and then import the library import JWTDecode and execute. What is a JSON Web Token? In short, a JWT is a small JSON payload consisting of a Header object, a Claims object and a signature. They are a self-contained way for securely transmitting information between parties. If you would like to know more about JWTs, please read our last blog post announcing the release of our Swift-JWT library or check out Importing Swift-JWT

Swift 4 as below:

if let data = Data(base64Encoded: base64String, options: []),
        let str = String(data: data as Data, encoding: String.Encoding.utf8) {
        print(str) // {"exp":1426822163,"id":"550b07738895600e99000001"}

Swift-JWT 3.0: Codable JSON web tokens, a Swift library for creating, signing, and verifying JSON web tokens. Codable conformance to the JWTs for easy encoding and decoding. JSON Web Tokens with Swift-JWT. Authorisation is an important part of any web service, and JSON Web Tokens, or JWTs, have risen in popularity in recent years and serve as an alternative to cookies and OAuth tokens. Swift-JWT is a new, powerful Swift library for creating, signing, and verifying JWTs, and it works seamlessly with Kitura.

JSON Web Tokens with Swift-JWT - Swift@IBM, JSON Web Tokens with Swift-JWT with access to the public key would then be able to reverse the encoding and verify the signature. Swift implementation of JSON Web Token. Swift Pacakage Manager is the recommended installation method for JSONWebToken, CocoaPods is also supported. pod 'JSONWebToken'. NOTE: Carthage may be supported, however support will not be provided for this installation method, use at your own risk if you know how it works.

JSON Web Tokens, The popular JSON Web Token format is a useful way to maintain authentication state and synchronise it between client and server. You are using JWTs as part  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.

Decoding JSON Web Tokens, iOS Swift: Authorization It is a JSON Web Token (JWT) that holds claims. You can use a JWT decoding library to obtain the roles and perform access control. Prior to Swift 4, parsing JSON was a common (yet cumbersome) process of dealing with untyped arrays and dictionaries. Now Swift comes with Codable, an incredibly powerful system for encoding and decoding types. There has been a number of great libraries for dealing with this task, but it is quite refreshing to see a fully-supported solution

  • where exactly should jwt tokens be stored as best practice? I've been thinking that it should be stored into keychain along with user name and password.
  • @user805981: I actually don't know anything about jwt tokens. But yes, sensitive data like passwords should be stored in the Keychain.
  • Thanks. Concerning keychains. How many keychain dictionaries is the keychain able to store per app? Is it infinite or one password keychain per app?
  • In Swift 4 it's better to use Data than NSData (and way better to use Data than to cast NSData to Data). And anyway, update for Swift 3+ has already been given by @raju-abe in their answer. Please do not post duplicate/incomplete content.