React-native fetch() from https server with self-signed certificate

前端 未结 7 1283
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-30 01:39

I\'m trying to communicate with https server having self-signed certificate.

I can do this from .NET application (using ServicePointManager.ServerCertificateValidati

7条回答
  •  孤城傲影
    2020-11-30 02:27

    Disclaimer: This solution should be temporary and documented so that it won't stay in the production phase of the software, this is for development only.

    For iOS, all you have to do is, open your xcodeproject (inside your iOS folder in RN) once you have that open, go to RCTNetwork.xcodeproj and in that project, navigate to RCTHTTPRequestHandler.m

    In that file you will see a line like this:

    #pragma mark - NSURLSession delegate
    

    right after that line, add this function

    - (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler
    {
      completionHandler(NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
    }
    

    And voila, you can now make insecure calls to your API without a valid certificate.

    That should be enough, but if you are still having problems, you might need to go to your project's info.plist, left click on it and choose open as... source code.

    and at the end just add

    NSAppTransportSecurity
      
        NSAllowsArbitraryLoads
        
      
      NSExceptionDomains
        
            localhost
            
                NSExceptionAllowsInsecureHTTPLoads
                
            
            subdomain.example.com
            
                NSIncludesSubdomains
                
                NSExceptionAllowsInsecureHTTPLoads
                
            
        
    

    so your file will look like this

        ...
        UISupportedInterfaceOrientations
        
            UIInterfaceOrientationPortrait
            UIInterfaceOrientationLandscapeLeft
            UIInterfaceOrientationLandscapeRight
        
        UIViewControllerBasedStatusBarAppearance
        
        NSLocationWhenInUseUsageDescription
        
      NSAppTransportSecurity
      
        NSAllowsArbitraryLoads
        
      
      NSExceptionDomains
        
            localhost
            
                NSExceptionAllowsInsecureHTTPLoads
                
            
            subdomain.example.com
            
                NSIncludesSubdomains
                
                NSExceptionAllowsInsecureHTTPLoads
                
            
        
    
    
    

    For a real production ready solution, https://stackoverflow.com/a/36368360/5943130 that solution is better

提交回复
热议问题