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)")
}
let token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJhY2NvdW56IiwianRpIjoiZTA0NGEyMTAtZjVmZi00Yjc2LWI2MzMtNTk0NjYzMWE0MjRjLWQxYTc3bXlpdGE0YnZnaG4yd2YiLCJleHAiOjE2NDk2NDI3MTF9.FO-AQhZ18qogsSbeTUY78EqhfL9xp9iUG3OlpOdxemE"
let jsonWebToken = JSONWebToken(jsonWebToken: token)
let expirationTime = jsonWebToken?.payload.expirationTime
JSONWebToken.swift
import Foundation
struct JSONWebToken {
let header: JSONWebTokenHeader
let payload: JSONWebTokenPayload
let signature: String
}
extension JSONWebToken {
init?(jsonWebToken: String) {
let encodedData = { (string: String) -> Data? in
var encodedString = string.replacingOccurrences(of: "-", with: "+").replacingOccurrences(of: "_", with: "/")
switch (encodedString.utf16.count % 4) {
case 2: encodedString = "\(encodedString)=="
case 3: encodedString = "\(encodedString)="
default: break
}
return Data(base64Encoded: encodedString)
}
let components = jsonWebToken.components(separatedBy: ".")
guard components.count == 3,
let headerData = encodedData(components[0] as String),
let payloadData = encodedData(components[1] as String) else { return nil }
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
do {
header = try decoder.decode(JSONWebTokenHeader.self, from: headerData)
payload = try decoder.decode(JSONWebTokenPayload.self, from: payloadData)
signature = components[2] as String
} catch {
print(error.localizedDescription)
return nil
}
}
}
JSONWebTokenHeader.swift
import Foundation
struct JSONWebTokenHeader {
let type: String
let algorithm: String
}
extension JSONWebTokenHeader: Codable {
private enum Key: String, CodingKey {
case type = "typ"
case algorithm = "alg"
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: Key.self)
do { try container.encode(type, forKey: .type) } catch { throw error }
do { try container.encode(algorithm, forKey: .algorithm) } catch { throw error }
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: Key.self)
do { type = try container.decode(String.self, forKey: .type) } catch { throw error }
do { algorithm = try container.decode(String.self, forKey: .algorithm) } catch { throw error }
}
}
JSONWebTokenPayload.swift
import Foundation
struct JSONWebTokenPayload {
let issuer: String
let expirationTime: Double
let jsonWebTokenID: String
}
extension JSONWebTokenPayload: Codable {
private enum Key: String, CodingKey {
case issuer = "iss"
case expirationTime = "exp"
case jsonWebTokenID = "jti"
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: Key.self)
do { try container.encode(issuer, forKey: .issuer) } catch { throw error }
do { try container.encode(expirationTime, forKey: .expirationTime) } catch { throw error }
do { try container.encode(jsonWebTokenID, forKey: .jsonWebTokenID) } catch { throw error }
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: Key.self)
do { issuer = try container.decode(String.self, forKey: .issuer) } catch { throw error }
do { expirationTime = try container.decode(Double.self, forKey: .expirationTime) } catch { throw error }
do { jsonWebTokenID = try container.decode(String.self, forKey: .jsonWebTokenID) } catch { throw error }
}
}
8条答案
按热度按时间voase2hg1#
如果你可以使用一个库,我建议你使用这个https://github.com/auth0/JWTDecode.swift。
然后导入库
import JWTDecode
并执行。因为你不想包含这个库,所以我拿出了所需的部分来使它工作。
这样称呼它:
xzv2uavs2#
迭代Viktor的代码:
希望有用:
j7dteeu83#
xxslljrj4#
我有办法了。
对我来说很好。谢谢。
8gsdolmq5#
有一个快速的实现。如果你正在使用CocoaPods,可以将其添加到你的Podfile中,或者克隆项目并直接使用它。
JSONWebToken
nzkunb0c6#
如果你想使用一个库,我建议使用一些流行的东西从某人大. IBM正在制作Kitura - Swift后端框架,所以它的编码和解码JWT的实现必须是一流的:
链接:https://github.com/IBM-Swift/Swift-JWT
带有到期日期的令牌的简单用法
kfgdxczn7#
Objective-C版本:
ifmq2ha28#
我重构了@Viktor Gardart代码
像这样使用
JSONWebToken.swift
JSONWebTokenHeader.swift
JSONWebTokenPayload.swift