JWT 的详细使用: 解析JWT
extension String {
func jwtDecode()->[String:Any]{
/**分割为数组*/
let segments = components(separatedBy:".")
/**获取第二个元素Payload负载元素(有意义的key就在里面解析的)*/
var base64String = segments[1]
/**base64解码*/
let requiredLength = (4*ceil((Float)(base64String.count)/4.0))
let nbrPaddings =Int(requiredLength) - base64String.count
if nbrPaddings >0{
let pading = "".padding(toLength: nbrPaddings,withPad:"=",startingAt:0)
base64String = base64String + pading
}
base64String = base64String.replacingOccurrences(of:"-",with:"+")
base64String = base64String.replacingOccurrences(of:"_",with:"/")
let decodeData =Data(base64Encoded: base64String,options:Data.Base64DecodingOptions.ignoreUnknownCharacters)
let decodeString =String.init(data: decodeData!,encoding:String.Encoding.utf8)
/**转为字典*/
let jsonDict:[String : Any]? = try? (JSONSerialization.jsonObject(with:(decodeString?.data(using: String.Encoding.utf8))!,options: JSONSerialization.ReadingOptions.mutableContainers) as! [String : Any])
/**返回jwt */
return jsonDict ?? [:]
}
}
网友评论