27

I want to allow invalid SSL certificates. My main code is below:

myClient = [[MyClient alloc] init];
[myClient getHtml:@"/path/to/the/distination.html"];

The MyClient class code is below:

#import <Foundation/Foundation.h>
#import "AFNetworking.h"

@interface MyClient : NSObject

- (void)getHtml:(NSString *)path;

@end

#define _AFNETWORKING_ALLOW_INVALID_SSL_CERTIFICATES_

@implementation MyClient

- (void)getHtml:(NSString *)path
{
    AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:@"https://trusted.server.net"]];
    [httpClient getPath:path parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"%@", responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"error = %@", error);
    }];
}

@end

I read below page and tried the macro but this doesn't work.

Self Signed certificate SSL · Issue #189 · AFNetworking/AFNetworking https://github.com/AFNetworking/AFNetworking/issues/189

Please help me...

Feel Physics
  • 2,783
  • 4
  • 25
  • 38

13 Answers13

45

In AFNetworking 2.0, you can use the following:

[AFHTTPRequestOperationManager manager].securityPolicy.allowInvalidCertificates = YES;
titaniumdecoy
  • 18,900
  • 17
  • 96
  • 133
  • That helps. I added "self.securityPolicy.allowInvalidCertificates = YES;" in AFHTTPRequestOperationManager init method. – Suvo08 K Jan 15 '16 at 19:41
41

To allow Invalid SSL Certificate with AFNetworking. Add the following line in AFURLConnectionOperation.h below #import Availability.h

#define _AFNETWORKING_ALLOW_INVALID_SSL_CERTIFICATES_ 1
Alex Terente
  • 12,006
  • 5
  • 51
  • 71
AvtarSingh Suchariya
  • 1,992
  • 1
  • 20
  • 25
  • 13
    As of version 1.2.1, you don't need anymore to set this define. Instead you can set the 'allowsInvalidSSLCertificate' property to YES on AFHTTPRequestOperation, which is much more convenient. – Phil May 16 '13 at 12:05
  • If you do this, make sure you are only doing it in debug mode. If you are hitting HTTPS endpoints and you allow invalid certs you're losing a good portion of the security you're getting from SSL. – Kyle Clegg Jun 26 '13 at 23:21
  • 6
    Is there any way to get allowsInvalidSSLCertificate to work with UIImageView+AFNetworking? – Ian Kershaw Jul 29 '13 at 10:54
  • In the latest version of AFNetworking (I'm running 2.2.3) you now need to use AFSecurityPolicy and set it as the 'security' property on AFHTTPRequestOperation. See http://stackoverflow.com/a/20815306/143979 for more info. – ingh.am Sep 14 '15 at 13:25
  • hello, i have add **#define _AFNETWORKING_ALLOW_INVALID_SSL_CERTIFICATES_ 1** in my project **AFURLConnectionOperation.h below #import Availability.h** file but i getting This Error in consol **Error: Error Domain=NSURLErrorDomain Code=-1012 "(null)" UserInfo={NSErrorFailingURLKey=my Url.com, NSErrorFailingURLStringKey=my Url.com}** @AvtarSingh Suchariya – Nikunj Mar 09 '18 at 12:09
24

You can now use the allowsInvalidSSLCertificate property of the AFHTTPClient. No need to use defines in the latest versions of AFNetworking.

AFHTTPClient* client = [AFHTTPClient clientWithBaseURL:@"url"];
client.allowsInvalidSSLCertificate = YES; //this defaults to no
David
  • 9,635
  • 5
  • 62
  • 68
12

I am using RestKit so

client.allowsInvalidSSLCertificate = YES;

does not work. The option is not propagated to the operations created by restkit.

I am using cocoapods so any changes in the pch file or the pods project get overriden. The "hack" I have been using is a cocoapod post-install operation that adds the required preprocessor definition. At the end of my pod file I have added:

post_install do |installer_representation|
  installer_representation.project.targets.each do |target|
    if target.name == 'Pods-AFNetworking'
      target.build_configurations.each do |config|
        config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] ||= ['$(inherited)']
        config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] << '_AFNETWORKING_ALLOW_INVALID_SSL_CERTIFICATES_=1'
      end
    end
  end
end
Sebastien Windal
  • 1,394
  • 12
  • 12
8

Note that if you are installing through CocoaPods, #define-ing this macro in your project will not be enough--the compiler macro must be set when compiling the static library in order for it to take effect.

mattt
  • 19,544
  • 7
  • 73
  • 84
5

Here's how you can do it using the manager for a POST operation.

 AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; //initialize
 manager.securityPolicy.allowInvalidCertificates=YES;    //allow unsigned
 manager.responseSerializer=[AFJSONResponseSerializer serializer];   //set up for JSOn  
 [manager POST:@"myweb.com" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
     //success stuff
 }failure:^(AFHTTPRequestOperation *operation, NSError *error) {
     //error stuff
}];

EDIT - swift version:

    var securityPolicy = AFSecurityPolicy()
    securityPolicy.allowInvalidCertificates = true;
    manager.securityPolicy = securityPolicy;
    manager.POST(
        "https://exmaple.com/foobar.php",
        nil,
    ...
elcuco
  • 8,948
  • 9
  • 47
  • 69
user3344717
  • 161
  • 3
  • 5
4

You should subclass the AFHttpClient,and override

- (AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)request 
                                                success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
                                                failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;

This is my code.

- (AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)urlRequest success:(void (^)(AFHTTPRequestOperation *, id))success failure:(void (^)(AFHTTPRequestOperation *, NSError *))failure
{
    AFHTTPRequestOperation *operation = [super HTTPRequestOperationWithRequest:urlRequest success:success failure:failure];

    [operation setAuthenticationAgainstProtectionSpaceBlock:^BOOL(NSURLConnection *connection, NSURLProtectionSpace *protectionSpace) {
        return YES;
    }];
    [operation setAuthenticationChallengeBlock:^(NSURLConnection *connection, NSURLAuthenticationChallenge *challenge) {
        if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
            [challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
        }
    }];
    return operation;
}

you use this httpclient and it can access self-unsigned web successfully.

jasonhao
  • 2,098
  • 1
  • 14
  • 7
  • Why do you need to subclass for this? Seems you could just add the protection space and authentication challenge blocks from anywhere, or am I missing something? – Carl Veazey Jan 20 '13 at 09:33
  • If you want to allow self-signed certs programmatically and still use AFHTTPClient, you need to do it this way. Unfortunately there's no equivalent `setAuthenticationAgainstProtectionSpaceBlock` for AFHTTPClient. – bobics Apr 18 '13 at 20:11
4

I extended AFHTTPSessionManager in my code. When testing against a test server, all I need is adding a single line like this:

mySessionManager.securityPolicy.allowInvalidCertificates = YES;
Golden Thumb
  • 2,531
  • 21
  • 20
3

AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:urlRequest]; operation.securityPolicy.allowInvalidCertificates = YES;

aqavi_paracha
  • 1,131
  • 2
  • 17
  • 38
2

if you are using RestKit using

client.allowsInvalidSSLCertificate = YES;

won't work, instead do this:

in your project, click on RestKit.xcodeproj go to project > Build Settings > Preprocessor Macros

and add _AFNETWORKING_ALLOW_INVALID_SSL_CERTIFICATES_=1

thats finished.

Hashem Aboonajmi
  • 13,077
  • 8
  • 66
  • 75
1

This is the best method for allowign invalid SSL certificates with AFNetworking.

use add a _AFNETWORKING_ALLOW_INVALID_SSL_CERTIFICATES_ to

project > Build Settings > Preprocessor Macros and add it to Debug entry.

Hope it Helps

1

if you are using RestKit using

client.allowsInvalidSSLCertificate = YES;

won't work, instead do this:

if you added rest kit manually to your project, click on RestKit.xcodeproj go to project > Build Settings > Preprocessor Macros

and add _AFNETWORKING_ALLOW_INVALID_SSL_CERTIFICATES_=1

thats finished.

Hashem Aboonajmi
  • 13,077
  • 8
  • 66
  • 75
0

I encountered the same problem and no one of the solutions that I read works.

For me the only workaround is set the AFSecurityPolicy like this:

AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
securityPolicy.allowInvalidCertificates = YES;
manager.securityPolicy = securityPolicy;

I decided to reply although the question is old, maybe can help someone.

Massimo Polimeni
  • 4,826
  • 4
  • 27
  • 54