How can I decode JWT (JSON web token) token in Swift?

jwt swift 4
swift jwt authentication
generate jwt token swift
swift-jwt tutorial
jwt decode
jwt token example
how to generate jwt token in ios

I have a JWT token like this


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

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

If you are okay with using a library i would suggest this

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)

IBM-Swift/Swift-JWT: JSON Web Tokens in Swift, JWT. The JWT struct represents the Header and Claims of a JSON Web Token. You can initialize a JWT by decoding a JWT  We have just released version 3.0 of Swift-JWT, our library for creating, signing, and verifying JSON Web Tokens. This release adds Codable conformance to the JWTs for easy encoding and decoding. This release adds Codable conformance to the JWTs for easy encoding and decoding.

    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
    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.Encoding.utf8.rawValue, allowLossyConversion: true) {
            values = try! JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments) as? [String : AnyObject]
    return values

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. Swift-JWT is a new, powerful Swift library for creating, signing, and verifying JWTs, and it works seamlessly with Kitura. Introduction to JSON Web Tokens As a brief introduction to JWTs for those who have never come across them before, they are a small JSON payload consisting of a Header object, a Claims object and a signature.

I have got the solution for this.

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

    var segments = tokenstr.components(separatedBy: ".")
    var base64String = segments[1]
    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))!
    return base64String as NSString

This works for me great. Thank you.

JSON Web Tokens, Swift-JWT 3.0: Codable JSON web tokens Tokens. This release adds Codable conformance to the JWTs for easy encoding and decoding. I have read that the token is coded in base64 and within this is the ID. Trying to decode, I see if the ID that I need is there. In swift with this function I decode the token, but I can not get the dictionary ID.

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


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

Swift-JWT 3.0: Codable JSON web tokens, JSON Web Tokens with Swift-JWT The Header object describes the JWT type and the algorithm used. print ( "Error decoding JWT" ). Swift implementation of JSON Web Token. Installation. Swift Pacakage Manager is the recommended installation method for JSONWebToken, CocoaPods is also supported. 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 with Swift-JWT - Swift@IBM, 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. You can use the JWTDecode  Faster JWT Token Decoder, Helps you to decode and validate JSON Web Token online and view the JWT token claims, Verify JWT Signature. JWT Decoder - Online Utility to Decode JWT. JSON Web Tokens are an open, industry standard RFC 7519 method for representing claims securely between two parties.

Auth0 iOS Swift SDK Quickstarts: Authorization, JSON Web Token. Build Status. Swift implementation of JSON Web Token. When decoding a JWT, you must supply one or more algorithms and keys. A library to help you decode JWTs in Swift. Contribute to auth0/JWTDecode.swift development by creating an account on GitHub. the token, any well formed JWT can

goodnighthsu/JSONWebToken.swift, A JSON Web Token implementation in Objective-C. errorHolder]]; // or add them in builder [JWTDecodingBuilder decodeMessage:token]. JSON Web Tokens are an open, industry standard RFC 7519 method for representing claims securely between two parties. JWT.IO allows you to decode, verify and generate JWT. Get the JWT Handbook for free! Download it now and get up-to-speed faster. Warning: JWTs are credentials, which can grant access to resources. Be careful where you paste them!

JWT on, The popular JSON Web Token format is a useful way to maintain You are using JWTs as part of your authentication process and you want to decode and validate the tokens at the edge Regardless, you're going to need to generate a JWT. 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

  • Thank you for the response. But I can not use the JWT library, I am implementing it in a framework, I want a simple implementation. In android I use String[] split = JWTEncoded.split("\\."); String body = getJson(split[1]); Log.d("JWT_DECODED", "Body: " + body); private static String getJson(String strEncoded) throws UnsupportedEncodingException{ byte[] decodedBytes = Base64.decode(strEncoded, Base64.URL_SAFE); return new String(decodedBytes, "UTF-8"); }
  • any other library with Swift 4 at least?
  • Generally, answers are much more helpful if they include an explanation of what the code is intended to do, and why that solves the problem without introducing others.
  • Didn't want to use external libraries, and this worked like a charm, thanks :)