Я хочу внедрить 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 = @"care_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
конфигурации сеанса:
Необработанные данные ответа SS:
Код: Выделить всё
Attention Required! | Cloudflare
body{margin:0;padding:0}
if (!navigator.cookieEnabled) {
window.addEventListener('DOMContentLoaded', function () {
var cookieEl = document.getElementById('cookie-alert');
cookieEl.style.display = 'block';
})
}
Please enable cookies.
Sorry, you have been blocked
You are unable to access test.example.com
Why have I been blocked?
This website is using a security service to protect itself from online attacks. The action you just performed triggered the security solution. There are several actions that could trigger this block including submitting a certain word or phrase, a SQL command or malformed data.
What can I do to resolve this?
You can email the site owner to let them know you were blocked. Please include what you were doing when this page came up and the Cloudflare Ray ID found at the bottom of this page.
Cloudflare Ray ID: [b]863c216f98813d2a[/b]
•
Your IP:
Click to reveal
206.84.236.234
•
Performance & security by [url=https://www.cloudflare.com/5xx-error-landing]Cloudflare[/url]
(function(){function d(){var b=a.getElementById("cf-footer-item-ip"),c=a.getElementById("cf-footer-ip-reveal");b&&"classList"in b&&(b.classList.remove("hidden"),c.addEventListener("click",function(){c.classList.add("hidden");a.getElementById("cf-footer-ip").classList.remove("hidden")}))}var a=document;document.addEventListener&&a.addEventListener("DOMContentLoaded",d)})();
window._cf_translation = {};
`
Мой файл info.plist**
Код: Выделить всё
`NSAppTransportSecurity
NSExceptionDomains
example.com
NSTemporaryExceptionAllowsInsecureHTTPLoads
NSIncludesSubdomains
NSTemporaryExceptionMinimumTLSVersion
TLSv1.2
NSTemporaryExceptionRequiresForwardSecrecy
NSExceptionRequiresForwardSecrecy
NSRequiresCertificateTransparency
NSAllowsArbitraryLoads
NSAllowsLocalNetworking
`
I have tried above code but getting 403.
Источник: https://stackoverflow.com/questions/781 ... ve-project