22
votes

I have a JWT token like this

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ

How can I decode this so that I can get the payload like this

{ "sub": "1234567890", "name": "John Doe", "admin": true }

6
Thanks for the question @SiddharthaChikatamalla ... Made my google search time a lot less!PhillipJacobs

6 Answers

59
votes

If you are okay with using a library i would suggest this https://github.com/auth0/JWTDecode.swift

and then import the library import JWTDecode and execute.

let jwt = try decode(jwt: token)

Since you didn't want to include this library i brought out the needed parts to make it work.

func decode(jwtToken jwt: String) -> [String: Any] {
  let segments = jwt.components(separatedBy: ".")
  return decodeJWTPart(segments[1]) ?? [:]
}

func base64UrlDecode(_ value: String) -> Data? {
  var base64 = value
    .replacingOccurrences(of: "-", with: "+")
    .replacingOccurrences(of: "_", with: "/")

  let length = Double(base64.lengthOfBytes(using: String.Encoding.utf8))
  let requiredLength = 4 * ceil(length / 4.0)
  let paddingLength = requiredLength - length
  if paddingLength > 0 {
    let padding = "".padding(toLength: Int(paddingLength), withPad: "=", startingAt: 0)
    base64 = base64 + padding
  }
  return Data(base64Encoded: base64, options: .ignoreUnknownCharacters)
}

func decodeJWTPart(_ value: String) -> [String: Any]? {
  guard let bodyData = base64UrlDecode(value),
    let json = try? JSONSerialization.jsonObject(with: bodyData, options: []), let payload = json as? [String: Any] else {
      return nil
  }

  return payload
}

Call it like this:

decode(jwtToken: TOKEN)
22
votes

Iterating on Viktor's code:

  • Wasn't sure why there were replacements for - and _ did not see that in any of my tokens.
  • Use nested functions to keep more modular
  • Utilize exceptions if bad token passed or other errors.
  • Simpler calculation of padding and utilization of padding function.

Hope it is useful:

func decode(jwtToken jwt: String) throws -> [String: Any] {

    enum DecodeErrors: Error {
        case badToken
        case other
    }

    func base64Decode(_ base64: String) throws -> Data {
        let padded = base64.padding(toLength: ((base64.count + 3) / 4) * 4, withPad: "=", startingAt: 0)
        guard let decoded = Data(base64Encoded: padded) else {
            throw DecodeErrors.badToken
        }
        return decoded
    }

    func decodeJWTPart(_ value: String) throws -> [String: Any] {
        let bodyData = try base64Decode(value)
        let json = try JSONSerialization.jsonObject(with: bodyData, options: [])
        guard let payload = json as? [String: Any] else {
            throw DecodeErrors.other
        }
        return payload
    }

    let segments = jwt.components(separatedBy: ".")
    return try decodeJWTPart(segments[1])
  }
10
votes
    func decode(_ token: String) -> [String: AnyObject]? {
    let string = token.components(separatedBy: ".")
    let toDecode = string[1] as String


    var stringtoDecode: String = toDecode.replacingOccurrences(of: "-", with: "+") // 62nd char of encoding
    stringtoDecode = stringtoDecode.replacingOccurrences(of: "_", with: "/") // 63rd char of encoding
    switch (stringtoDecode.utf16.count % 4) {
    case 2: stringtoDecode = "\(stringtoDecode)=="
    case 3: stringtoDecode = "\(stringtoDecode)="
    default: // nothing to do stringtoDecode can stay the same
        print("")
    }
    let dataToDecode = Data(base64Encoded: stringtoDecode, options: [])
    let base64DecodedString = NSString(data: dataToDecode!, encoding: String.Encoding.utf8.rawValue)

    var values: [String: AnyObject]?
    if let string = base64DecodedString {
        if let data = string.data(using: String.Encoding.utf8.rawValue, allowLossyConversion: true) {
            values = try! JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments) as? [String : AnyObject]
        }
    }
    return values
}
3
votes

There's a swift implementation. Add this into your Podfile if you're using CocoaPods or clone the project and use it directly.

JSONWebToken

do {
  // the token that will be decoded
  let token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ"
  let payload = try JWT.decode(token, algorithm: .hs256("secret".data(using: .utf8)!))
  print(payload)
} catch {
  print("Failed to decode JWT: \(error)")
}
3
votes

I have got the solution for this.

 static func getJwtBodyString(tokenstr: String) -> NSString {

    var segments = tokenstr.components(separatedBy: ".")
    var base64String = segments[1]
    print("\(base64String)")
    let requiredLength = Int(4 * ceil(Float(base64String.characters.count) / 4.0))
    let nbrPaddings = requiredLength - base64String.characters.count
    if nbrPaddings > 0 {
        let padding = String().padding(toLength: nbrPaddings, withPad: "=", startingAt: 0)
        base64String = base64String.appending(padding)
    }
    base64String = base64String.replacingOccurrences(of: "-", with: "+")
    base64String = base64String.replacingOccurrences(of: "_", with: "/")
    let decodedData = Data(base64Encoded: base64String, options: Data.Base64DecodingOptions(rawValue: UInt(0)))
  //  var decodedString : String = String(decodedData : nsdata as Data, encoding: String.Encoding.utf8)

    let base64Decoded: String = String(data: decodedData! as Data, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue))!
    print("\(base64Decoded)")
    return base64String as NSString
}

This works for me great. Thank you.

3
votes

I you want to use a library for that I recommend using something popular from someone big. IBM is making Kitura – Swift backend framework, so the implementation of encoding and decoding JWT for it must be top notch:

Link: https://github.com/IBM-Swift/Swift-JWT

Simple usage for token with expiry date

import SwiftJWT

struct Token: Decodable {
    let jwtString: String

    func abc() {

        do {
            let newJWT = try JWT<MyJWTClaims>(jwtString: jwtString)
            print(newJWT.claims.exp)
        } catch {
            print("OH NOES")
        }


    }
}

struct MyJWTClaims: Claims {
    let exp: Date
}