Skip to content

Instantly share code, notes, and snippets.

@AlexHedley
Last active April 6, 2021 02:14
Show Gist options
  • Save AlexHedley/2b7d3b377e64f9407589ddf95b11ca1f to your computer and use it in GitHub Desktop.
Save AlexHedley/2b7d3b377e64f9407589ddf95b11ca1f to your computer and use it in GitHub Desktop.
Parse a JWT - JSON Web Token
//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
@AppleCEO
Copy link

Thank you

@timothy-20
Copy link

awesome

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment