我正在构建一个iOS应用程序,需要使用下面链接中概述的OAuth 2.0/JWT工作流与Google进行身份验证。
Google OAuth 2.0 JWT示例
我有私钥文件和client_id。我正在使用谷歌API Objective-C客户端库来尝试和认证。但是,我不知道如何继续。
是否可以使用iOS客户端库进行此身份验证工作流?
我刚刚完成了类似你的问题。我需要使用JWT将数据发布到GCP IoT。以下是我使用RSAWithSHA256所做的:
使用MIHCrypto库(在Podfile pod "MIHCrypto", "~> 0.4.1")
#import "MIHAESKeyFactory.h"
#import "MIHRSAPrivateKey.h"
(void) createJWT {
NSMutableDictionary *headerDict = [NSMutableDictionary new];
headerDict[@"alg"] = @"RS256";
headerDict[@"typ"] = @"JWT";
NSMutableDictionary *payloadDict = [NSMutableDictionary new];
payloadDict[@"aud"] = @"my project";
NSDate *now = [NSDate new];
payloadDict[@"iat"] = [NSNumber numberWithInt:[now timeIntervalSince1970]];
payloadDict[@"exp"] = [NSNumber numberWithInt:[now timeIntervalSince1970] + 20 * 60];
NSError *error;
NSData *headerData = [NSJSONSerialization dataWithJSONObject:headerDict
options:NSJSONWritingPrettyPrinted
error:&error];
NSData *payloadData = [NSJSONSerialization dataWithJSONObject:payloadDict
options:NSJSONWritingPrettyPrinted
error:&error];
NSString *base64UrlMessage = [NSString stringWithFormat:@"%@.%@", [self base64UrlforData:headerData ], [self base64UrlforData:payloadData]];
NSData *privateKeyData = [[self pemKeyStringFromFileWithName:@"myPrivateKey" extension:@"pem"] dataUsingEncoding:NSUTF8StringEncoding];
MIHRSAPrivateKey *privateKey = [[MIHRSAPrivateKey alloc] initWithData:privateKeyData];
NSError *signingError = nil;
NSData *signedData = [privateKey signWithSHA256:[base64UrlMessage dataUsingEncoding:NSUTF8StringEncoding] error:&signingError];
NSString *signedBase64UrlMessage = [self base64UrlforData: signedData];
NSString *jwt = [NSString stringWithFormat:@"%@.%@", base64UrlMessage, signedBase64UrlMessage];
NSLog(@"jwt = %@", jwt);
}
(NSString*)base64UrlforData:(NSData*)data {
// base64 to base64URL
// 1 - remove all '='
// 2 - replace all '+' by '-'
// 3 - replace all '/' by '_'
NSString *base64 = [data base64EncodedStringWithOptions:0];
NSString *base64_1 = [base64 stringByReplacingOccurrencesOfString:@"=" withString:@""];
NSString *base64_2 = [base64_1 stringByReplacingOccurrencesOfString:@"+" withString:@"-"];
NSString *base64_3 = [base64_2 stringByReplacingOccurrencesOfString:@"/" withString:@"_"];
return base64_3;
}
(NSString *)pemKeyStringFromFileWithName:(NSString *)name extension: (NSString*) extension {
NSBundle *bundle = [NSBundle mainBundle];
NSURL *fileURL = [bundle URLForResource:name withExtension:extension];
NSError *error = nil;
NSString *fileContent = [NSString stringWithContentsOfURL:fileURL encoding:NSUTF8StringEncoding error:&error];
if (error) {
NSLog(@"%@ error: %@", self.debugDescription, error);
return nil;
}
return fileContent;
}