Validate JWT token with RS256 or RS512 with Swift iOS

风流意气都作罢 提交于 2019-12-04 13:16:22

Not sure if you are still stuck on this, but I was in the exact same situation and it took a while to figure out. I ended up using the JWT pod and was pushed in the right direction by this article. I'll summarize my findings.

Due to Apple dropping OpenSSL in favor of their own Security libs the input has to be a self signed certificate containing the public key. With OpenSSL do something like this using your private key as input:

openssl req -key private_key.pem -new -x509 -days 3650 -out selfsigned_cert.pem

Then convert the PEM format to DER, which is basically removing the b64 armoring:

openssl x509 -outform der -in selfsigned_cert.pem -out selfsigned_cert.der

Add the .der file to Supporting Files in your Xcode project and then read the certificate data from disk and base64 encode it:

NSURL *fileURL = [NSURL fileURLWithPath:[bundle pathForResource: @"selfsigned_cert" ofType:@"der"]];
NSData *certificateData = [NSData dataWithContentsOfURL:fileURL];
// Probably want to do a nil-check on certificateData here
NSString *certificateStr = [JWTBase64Coder base64UrlEncodedStringWithData:certificateData];

And then plug it into the JWT decoder:

JWTBuilder *decodeBuilder = [JWTBuilder decodeMessage:token] // your JWT
  .secret(certificateStr)
  .algorithmName(algorithmName); // From your token or a predefined string
NSDictionary *payload = decodeBuilder.decode;

You can check if the decoding/verification was successful or not by checking for an error in the builder:

if(decodeBuilder.jwtError != nil) { /* do stuff */ }

Edit: As a side note. Converting to DER and then b64 encode it might seem redundant, it basically just removes the anchor lines from the PEM format. The reason why I have a .der file on disk is because that's what we can use directly with the Security libs if we need to.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!