-
-
Save AppleCEO/fda9a724670880b2b568a51a42148d8b to your computer and use it in GitHub Desktop.
Parse a JWT - JSON Web Token
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//DECODE JSON WEB TOKEN (JWT) IN IOS (OBJECTIVE-C) | |
//http://popdevelop.com/2013/12/decode-json-web-token-jwt-in-ios-objective-c/ | |
NSString *jwt = @"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJmb28iOiJiYXIifQ.bVhBeMrW5g33Vi4FLSLn7aqcmAiupmmw-AY17YxCYLI"; | |
NSArray *segments = [jwt componentsSeparatedByString:@"."]; | |
NSString *base64String = [segments objectAtIndex: 1]; | |
NSLog(@"%@", base64String); | |
// => "eyJmb28iOiJiYXIifQ" | |
int requiredLength = (int)(4 * ceil((float)[base64String length] / 4.0)); | |
int nbrPaddings = requiredLength - [base64String length]; | |
if (nbrPaddings > 0) { | |
NSString *padding = [[NSString string] stringByPaddingToLength:nbrPaddings withString:@"=" startingAtIndex:0]; | |
base64String = [base64String stringByAppendingString:padding]; | |
} | |
base64String = [base64String stringByReplacingOccurrencesOfString:@"-" withString:@"+"]; | |
base64String = [base64String stringByReplacingOccurrencesOfString:@"_" withString:@"/"]; | |
NSData *decodedData = [[NSData alloc] initWithBase64EncodedString:base64String options:0]; | |
NSString *decodedString = [[NSString alloc] initWithData:decodedData encoding:NSUTF8StringEncoding]; | |
NSLog(@"%@", decodedString); | |
// => "{\"foo\":\"bar\"}" | |
NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:[decodedString dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil]; | |
NSLog(@"%@", jsonDictionary); | |
// => { foo = bar; } | |
// --- | |
// Now parse the Date | |
// { | |
// exp = 1493023908; //"exp": (Date.now() / 1000) + 60 | |
// iss = "http://localhost/"; | |
// nbf = 1493022108; | |
// } | |
NSNumber *timeInterval = [jsonDictionary valueForKey:@"exp"]; | |
NSDate *date2 = [NSDate dateWithTimeIntervalSince1970:[timeInterval integerValue]]; | |
NSLog(@"timeInterval:%@ = date:%@ ", timeInterval, date2); | |
NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; | |
[formatter setDateFormat:@"dd-MM-yyyy hh:mm:ss"]; | |
//Optionally for time zone conversions | |
//[formatter setTimeZone:[NSTimeZone timeZoneWithName:@"..."]]; | |
NSString *stringFromDate = [formatter stringFromDate:date2]; | |
//The Anatomy of a JSON Web Token | |
//https://scotch.io/tutorials/the-anatomy-of-a-json-web-token | |
//JWT = header.payload.signature | |
//https://www.jsonwebtoken.io | https://www.jwtinspector.io |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment