iOS - Auth验证jwt解析(decode)token原生方法
2017-03-29 10:51 菜鸟Alex 阅读(6706) 评论(0) 编辑 收藏 举报- 一个方法搞定
- 参数
jwtStr
是从Auth获取的token字符串 - 返回内容
jsonDict
是字典.
-(id)jwtDecodeWithJwtString:(NSString *)jwtStr{
NSArray * segments = [jwtStr componentsSeparatedByString:@"."];
NSString * base64String = [segments objectAtIndex:1];
int requiredLength = (int)(4 *ceil((float)[base64String length]/4.0));
int nbrPaddings = requiredLength - (int)[base64String length];
if(nbrPaddings > 0){
NSString * pading = [[NSString string] stringByPaddingToLength:nbrPaddings withString:@"=" startingAtIndex:0];
base64String = [base64String stringByAppendingString:pading];
}
base64String = [base64String stringByReplacingOccurrencesOfString:@"-" withString:@"+"];
base64String = [base64String stringByReplacingOccurrencesOfString:@"_" withString:@"/"];
NSData * decodeData = [[NSData alloc] initWithBase64EncodedData:base64String options:0];
NSString * decodeString = [[NSString alloc] initWithData:decodeData encoding:NSUTF8StringEncoding];
NSDictionary * jsonDict = [NSJSONSerialization JSONObjectWithData:[decodeString dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
return jsonDict;
}
参考来源: http://popdevelop.com/2013/12/decode-json-web-token-jwt-in-ios-objective-c/