在 Swift 中解码 JSON 个网络令牌

Decoding JSON Web Tokens in Swift

尝试在 Swift 中解码 JWT 有效负载并且遇到了非常困难的时间

static func decodePayload(tokenstr: String) {

    //splitting JWT to extract payload
    let arr = split(tokenstr) {[=12=] == "."}

    //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)!


}
eyJleHAiOjE0MjY4MjIxNjMsImlkIjoiNTUwYjA3NzM4ODk1NjAwZTk5MDAwMDAxIn0

不是有效的 Base64 编码字符串,因为它的长度 不是 4 的倍数。一些 Base64 解码器容忍这个错误,但是 NSData 方法没有。

所以这实际上是服务器端创建 Base64 编码的字符串。如有必要,您可以在您的应用程序中修复它 通过使用 = 个字符添加所需的填充(针对 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("="))
}

现在解码工作正常:

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"}
}

上面的解决方案对我有用,我转换成swift3

在这里你可以找到swift3代码

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) {
        print(str)
}

Swift 4如下:

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