Это сертификат необходимо для доступа к API, поскольку на сервере установлены правила, позволяющие принимать запросы только с действительными сертификатами.
Однако я не знаком с разработкой iOS, и мне нужны инструкции о том, как встроить эти сертификаты в мое приложение React Native для iOS.
Мой существующий код iOS написан на Objective C++, например (AppDelegate.mm)
Может ли кто-нибудь предоставить подробные пошаговые инструкции о том, как это сделать?
Любая информация или примеры кода были бы очень признательны.
Спасибо!
Я пробовал следовать рекомендациям
MyURLSessionDelegate.h
Код: Выделить всё
#import
@interface MyURLSessionDelegate : NSObject
+ (instancetype)sharedInstance;
- (NSURLSession *)configuredSession;
@end
Код: Выделить всё
#import "MyURLSessionDelegate.h"
#import
@implementation MyURLSessionDelegate
+ (instancetype)sharedInstance {
static MyURLSessionDelegate *sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [[MyURLSessionDelegate alloc] init];
});
return sharedInstance;
}
- (NSURLSession *)configuredSession {
NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
// Load the client certificate
NSString *pathToCertificate = [[NSBundle mainBundle] pathForResource:@"xyz_certificateName" ofType:@"pem"];
NSData *certificateData = [NSData dataWithContentsOfFile:pathToCertificate];
if (!certificateData) {
NSLog(@"Client certificate not found");
return nil;
}
// Create a custom SSL configuration with the client certificate
NSDictionary *sslSettings = @{
(NSString *)kCFStreamSSLCertificates: @[certificateData],
(NSString *)kCFStreamSSLValidatesCertificateChain: @NO // Disable certificate chain validation if needed
};
sessionConfig.TLSMinimumSupportedProtocol = kTLSProtocol1;
sessionConfig.TLSMaximumSupportedProtocol = kTLSProtocol12;
sessionConfig.TLSMinimumSupportedProtocol = kTLSProtocol12;
sessionConfig.TLSMaximumSupportedProtocol = kTLSProtocol13;
sessionConfig.connectionProxyDictionary = sslSettings;
// Create and return NSURLSession with custom configuration and delegate
return [NSURLSession sessionWithConfiguration:sessionConfig delegate:self delegateQueue:nil];
}
#pragma mark - NSURLSessionDelegate Methods
// Implement NSURLSessionDelegate methods as needed
@end
Код: Выделить всё
#import "AppDelegate.h"
#import
#import
#import
#import
#import
#import "MyURLSessionDelegate.h"
#import "SSLPinning.h"
#import "ClientSecurity.h"
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[FIRApp configure];
self.moduleName = @“xyz_app";
self.initialProps = @{};
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
center.delegate = self;
NSURLSession *session = [[MyURLSessionDelegate sharedInstance] configuredSession];
NSLog(@"session configuration: %@", session.configuration);
// Create the URL
NSURL *url = [NSURL URLWithString:@"https://xyz.example.com/rest/login"];
// Create the request
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"POST";
// Set the parameters
NSDictionary *parameters = @{@"username": @“example”, @"password": @“Example@123};
NSData *postData = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:nil];
// Set the request body
[request setHTTPBody:postData];
// Set the content type
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
// Create a data task with the session
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
// Check for errors
if (error) {
NSLog(@"SS Error: %@", error);
return;
}
// Log the raw response data
NSLog(@"SS Raw Response Data: %@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
// Parse the response data (assuming it's JSON for example)
NSError *jsonError = nil;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonError];
// Check for JSON parsing errors
if (jsonError) {
NSLog(@"SS JSON Error: %@", jsonError);
return;
}
NSLog(@"SS Response: %@", json);
}];
[dataTask resume];
@end
Мой запрос блокируется Cloudflare.
Вкл. API-вызов, который я получаю => [AxiosError: запрос не выполнен с кодом состояния 403]
Подробнее здесь: https://stackoverflow.com/questions/781 ... native-ios