oc 解析jwt 和过期时间计算
- (void)viewDidLoad {
[super viewDidLoad];
NSString *jwt_str = @"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoyLCJ1c2VybmFtZSI6ImtlZXBfaXQiLCJleHAiOjE1NTk0ODcyODIsImVtYWlsIjoiZG9uZ3NoYW5ndG9uZ0AxNjMuY29tIn0.BuP6QJlnY-UWtpzh4H2_ippVoLCNWGgon8jp1dBVWPE";
NSLog(@"%@", [self jwtDecodeWithJwtString:jwt_str]);
}
-(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;
}
-(NSString *)token {
NSString *token = [[NSUserDefaults standardUserDefaults] objectForKey:@"kLoginToken"];
NSLog(@"server token %@",token);
if (token) {
NSDictionary *dict = [self jwtDecodeWithJwtString:token];
NSLog(@"server token dict %@",dict);
if ([dict objectForKey:@"exp"]) {
NSNumber *exp = [dict objectForKey:@"exp"];//时间戳
NSTimeInterval time = exp.floatValue + 28800;//因为时差问题要加8小时 == 28800 sec
NSDate *detaildate = [NSDate dateWithTimeIntervalSince1970:time];
NSLog(@"server token date:%@",[detaildate description]);
//日历
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *currentDate = [NSDate date];
//计算两个日期的差值
NSDateComponents*cmps= [calendar components:NSCalendarUnitDay fromDate:currentDate toDate:detaildate options:NSCalendarMatchStrictly];
NSLog(@"server token 时间差值--->%@",cmps);
if (cmps.day <= 1) {
//如果token过期,则清除token
// [self clearToken];
return nil;
}
}
}
return token;
}
网友评论