1、使用第三方库 AFNetworking进行网络请求。
2、阿里云函数计算签名认证文档
3、文档中添加 CanonicalizedFCHeaders 可以不用添加,CanonicalizedResource如何没有设置Path,在末尾加入“/”就可以了。
4、主要还是 hmac-sha256 签名认证,在实现过程中转base64的问题。
下面则是实现代码:文章来源地址https://www.toymoban.com/news/detail-604148.html
+ (AFHTTPSessionManager *)httpSessionManager:(NSString *)url{
AFHTTPSessionManager *sessionManager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:url]];
sessionManager.requestSerializer = [AFJSONRequestSerializer serializer];
sessionManager.responseSerializer = [AFJSONResponseSerializer serializer];
sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", nil];
[sessionManager.requestSerializer setValue:[YTDWindingCalculatorHttp aliSignature:sessionManager] forHTTPHeaderField:@"Authorization"];
return sessionManager;
}
+ (NSString *)aliSignature:(AFHTTPSessionManager *)sessionManager{
NSString *accessKeyID = @"xxxxxx";
NSString *accessKeySecret = @"xxxx";
NSString *authorization = [NSString stringWithFormat:@"FC %@:",accessKeyID];
NSMutableArray *signatureArray = [NSMutableArray array];
[signatureArray addObject:@"POST"];
[signatureArray addObject:@""];
[signatureArray addObject:@"application/json"];
NSString *date = [YTDWindingCalculatorHttp rfc1123String];
[signatureArray addObject:date];
[signatureArray addObject:@"/\n"];
//请求头添加content-type 和 date
[sessionManager.requestSerializer setValue:sessionManager.responseSerializer.acceptableContentTypes.allObjects.firstObject forHTTPHeaderField:@"content-type"];
[sessionManager.requestSerializer setValue:date forHTTPHeaderField:@"date"];
NSString *signature = [signatureArray componentsJoinedByString:@"\n"];
signature = [YTDWindingCalculatorHttp hmac:signature withKey:accessKeySecret];
authorization = [NSString stringWithFormat:@"%@%@",authorization,signature];
return authorization;
}
+ (NSString *)hmac:(NSString *)content withKey:(NSString *)secret{
const char *cKey = [secret cStringUsingEncoding:NSUTF8StringEncoding];
const char *cData = [content cStringUsingEncoding:NSUTF8StringEncoding];// 有可能有中文 所以用NSUTF8StringEncoding -> NSASCIIStringEncoding
unsigned char cHMAC[CC_SHA256_DIGEST_LENGTH];
CCHmac(kCCHmacAlgSHA256, cKey, strlen(cKey), cData, strlen(cData), cHMAC);
NSData *HMACData = [NSData dataWithBytes:cHMAC length:sizeof(cHMAC)];
NSData *base64Data = [HMACData base64EncodedDataWithOptions:NSDataBase64Encoding64CharacterLineLength];
return [[NSString alloc] initWithData:base64Data encoding:NSUTF8StringEncoding];
}
+ (NSString *)rfc1123String{
time_t date = (time_t)[[NSDate date] timeIntervalSince1970];
struct tm timeinfo;
gmtime_r(&date, &timeinfo);
char buffer[32];
size_t ret = strftime_l(buffer, sizeof(buffer), "%a, %d %b %Y %H:%M:%S GMT", &timeinfo, NULL);
if (ret) {
return @(buffer);
} else {
return nil;
}
}
文章来源:https://www.toymoban.com/news/detail-604148.html
到了这里,关于阿里云函数计算签名认证(iOS实现细节备注)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!