Закрепление SSL-сертификата в приложении iOS с использованием цели C для React Native ProjectIOS

Программируем под IOS
Ответить Пред. темаСлед. тема
Anonymous
 Закрепление SSL-сертификата в приложении iOS с использованием цели C для React Native Project

Сообщение Anonymous »

Я хочу внедрить SSL-сертификат клиента для приложения iOS, используя цель C для моего собственного проекта React.
Я пробовал множество решений, но безуспешно.
Итак, у нас есть SSL-сертификат клиента (.pem), который нам нужно встроить, чтобы наш API работал. Я получаю ошибку 403 при вызове нашего API. Делюсь своим кодом.

Код: Выделить всё

**MyURLSessionDelegate.mm**

#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];
NSLog(@"MyURLSessionDelegate=====>working=====>line 16 : %@", sessionConfig);

// Load the client certificate
NSString *pathToCertificate = [[NSBundle mainBundle] pathForResource:@"xyz" ofType:@"pem"];
NSLog(@"pathToCertificate ====> : %@", pathToCertificate);
NSData *certificateData = [NSData dataWithContentsOfFile:pathToCertificate];
NSLog(@"MyURLSessionDelegate=====>working=====>line 21 : %@", certificateData);
NSString *base64Certificate = [certificateData base64EncodedStringWithOptions:0];
NSLog(@"Base64 Encoded Certificate: %@", base64Certificate);

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

Код: Выделить всё

**AppDelegate.mm**

#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://test.example.com];

// 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;

}

// Now you can work with the JSON response

NSLog(@"SS Response: %@", json);

}];

// Resume the task to start the request

[dataTask resume];

return [super application:application didFinishLaunchingWithOptions:launchOptions];

}

- (NSURL *)sourceURLForBridge:(RCTBridge *)bridge

{

#if DEBUG

return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index"];

#else

return [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];

#endif

}

// Required for the register event.

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken

{

[RNCPushNotificationIOS didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];

}

// Required for the notification event.  You must call the completion handler after handling the remote notification.

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo

fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler

{

[RNCPushNotificationIOS didReceiveRemoteNotification:userInfo fetchCompletionHandler:completionHandler];

}

// Required for the registrationError event.

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error

{

[RNCPushNotificationIOS didFailToRegisterForRemoteNotificationsWithError:error];

}

// Required for localNotification event

- (void)userNotificationCenter:(UNUserNotificationCenter *)center

didReceiveNotificationResponse:(UNNotificationResponse *)response

withCompletionHandler:(void (^)(void))completionHandler
{
[RNCPushNotificationIOS didReceiveNotificationResponse:response];
}

//Called when a notification is delivered to a foreground app.

-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler {
completionHandler(UNNotificationPresentationOptionSound | UNNotificationPresentationOptionAlert | UNNotificationPresentationOptionBadge);
}

@end
Я получаю следующую ошибку
конфигурации сеанса:

**
Мой файл info.plist**

Код: Выделить всё

`NSAppTransportSecurity

NSExceptionDomains

example.com 

NSTemporaryExceptionAllowsInsecureHTTPLoads

NSIncludesSubdomains

NSTemporaryExceptionMinimumTLSVersion
TLSv1.2
NSTemporaryExceptionRequiresForwardSecrecy

NSExceptionRequiresForwardSecrecy

NSRequiresCertificateTransparency

NSAllowsArbitraryLoads

NSAllowsLocalNetworking




`
Дайте мне знать, что здесь не так.
Я попробовал приведенный выше код, но получил ошибку 403.

Подробнее здесь: https://stackoverflow.com/questions/781 ... ve-project
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «IOS»