How to Respond to an Authentication Challenge | iOS

How to Respond to an Authentication Challenge

If a session requires authentication it creates authentication challenge

 URLSession:task:didReceiveChallenge:completionHandler: 

in order for the connection to continue, the delegate has three options.

  • Provide authentication credentials
  • Attempt to continue without credentails
  • Cancel the authentication request.

NSURLProtectionSpace will give all information about the authentication type and failure if any attempts failed earlier.

Providing Credentials

To attempt to authenticate, the application should create an NSURLCredential object with authentication information of the form expected by the server. You can determine the server’s authentication method by calling authenticationMethod on the protection space.

  • HTTP basic authentication (NSURLAuthenticationMethodHTTPBasic) requires a user name and password. P
  • HTTP digest authentication (NSURLAuthenticationMethodHTTPDigest), like basic authentication, requires a user name and password.withcredentialWithUser:password:persistence:.
  • Client certificate authentication (NSURLAuthenticationMethodClientCertificate) requires the system identity and all certificates needed to authenticate with the server. Create an NSURLCredential object.
  • Server trust authentication (NSURLAuthenticationMethodServerTrust) requires a trust provided by the protection space of the authentication challenge.

Continuing Without Credentials

If the delegate chooses not to provide a credential for the authentication challenge, it can attempt to continue without one.

NSURLSessionAuthChallengePerformDefaultHandling processes the request as though the delegate did not provide a delegate method to handle the challenge.

  • NSURLSessionAuthChallengeRejectProtectionSpace rejects the challenge. Depending on the authentication types allowed by the server’s response, the URL loading class may call this delegate method more than once, for additional protection spaces.

Canceling the Connection

The delegate may also choose to cancel the authentication challenge, by passing NSURLSessionAuthChallengeCancelAuthenticationChallenge to the provided completion handler block.

Dependency Injection | Swift | Quick Note

A short answer is, it’s scary terms for a very simple idea!!! See this lines of code.

class Engine {

}

class Car {
    let engine: Engine? = nil
    init() {
        self.engine = Engine()
    }
}

we are creating dependency internally but the object can be also received from outside with lots of benefits like the object become instantly testable, Testing becomes possible without any frameworks, No runtime effects, This makes the whole system more loosely coupled.

class Car {
    let engine: Engine? = nil
    init(engine: Engine) {
        self.engine = engine
    }
}

There are three common types of dependency injections.

Setter, Interface, Constructor based.

In iOS Constructor based is preferable one, it’s when dependency passed to the client in the initializer and don’t change during the whole client life and the biggest advantage of this type could be that it makes the violation of the single responsibility programming principle, if an object takes all dependencies in the initializer and if it has more than three parameters so it means refactoring is needed.

Thanks for reading!!!

Swift | iOS 10 | Orientation | Quick Notes

When it comes to handling Orientation in iOS App Development, creates little confusion because with every release their minor changes. so let’s see who does it works with iOS 10.

First thing if you want to support all Orientations just enable it from here.

Screen Shot 2017-08-02 at 3.40.51 PM.png

Second, if the requirement is something like, need Orientation support only for few Controllers. make sure you have followed the first case and just this code snippet for enabling/disable it for each view.

override var shouldAutorotate: Bool {
    return true
}

its simple as its looking just return `true` if you want to support orientation for controller else return `false`. Next concern is if you are returning true then you have an option to specify the orientations as well just implement this code snippet.

override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
    return UIInterfaceOrientationMask.all
} 

Click `UIInterfaceOrientationMask` to see the options so just return whatever you want to use. Sounds good?

public struct UIInterfaceOrientationMask : OptionSet {
    public init(rawValue: UInt)
    public static var portrait: UIInterfaceOrientationMask { get }
    public static var landscapeLeft: UIInterfaceOrientationMask { get }
    public static var landscapeRight: UIInterfaceOrientationMask { get }
    public static var portraitUpsideDown: UIInterfaceOrientationMask { get }
    public static var landscape: UIInterfaceOrientationMask { get }
    public static var all: UIInterfaceOrientationMask { get }
    public static var allButUpsideDown: UIInterfaceOrientationMask { get }
}

Thank you for reading.

Make your iOS apps more secure with SSL pinning

SSL/Certificate pinning plays a very critical role in building highly secure mobile apps which users will be able to use even in countless insecure wireless network connections.

At a glance, Idea is the SSL(Secure Socket Layer) ensures the encrypted client-server communication over HTTPS. The encryption is based on PKI (Public Key Infrastructure) and a session key. The session key was introduced because encrypting and decrypting a public/private key uses a lot of processing time/power/space for sure it will slow down the process.

MIMT, Yes SSL Communication is very secure but the man-in-the-middle attack still poses an exact threat using ARP cache poisoning and DNS spoofing.

SSL/Certificate Pinning, ensure that the app communicates only with the designated server only and the prerequisites for SSL pinning is saving the target’s server SSL certificate within the app bundle.

SSL pinning is implemented within the

    func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void

and here are the steps we need to follow.

  • First read the server trust and server certificate.

let serverTrust = challenge.protectionSpace.serverTrust
let certificate = SecTrustGetCertificateAtIndex(serverTrust, 0

  • Now set the policies for server validation, previous failure count etc.

SecTrustSetPolicies(serverTrust, SecPolicyCreateSSL(true, (challenge.protectionSpace.host as CFString)))

  • Start policies validation, convert server certificate in Data and get the local certificate from bundle.

 let remoteCertificateData = SecCertificateCopyData(certificate)
 let pathToCert = Bundle.main.path(forResource: “certificate”, ofType: “cer”

At last compare your policies result and local certificate data with your server certificate data, if everything goes well complete the challange with credentail.

completionHandler(.UseCredential, credential)

Otherwise cancel the authentication and pass nil as credentails.

completionHandler(.CancelAuthenticationChallenge, nil)

Thank you reading, you can download the source code from GIT and also learn contribute about iOS Security.

WWDC June 2017 | Keynote

  • tvOS: Introduced Amazon prime video Integration with Apple tvOS.Screen Shot 2017-06-05 at 10.45.41 PM.png
  • Apple Watch: watchOS 4 released with lots of amazing features like Apple watch Siri faces (upcoming events and weather, traffic. integration of AI make it more confident and accurate), cloudy displays and more mickey characters. Also they have Enhances lots of Apps like  Workout: High intensity training, Music For Siri.
  • macOS High Sierra: All about deep technology, lots of refinements in safari like auto play blocking, Intelligent tracking prevention. Refinements in Mail, Photos (Filtering, Face recognition(sycn across all devices, Photo editing tools)). Apple file system for macOS introduced its,  H265 new standard for videos. Metal 2 for graphics, video cut pro. Steam VR SDK – 90 frames per seconds for desining new VR expereice,  thunderbold 3.Screen Shot 2017-06-05 at 11.21.45 PM.png
  • iOS: iOS 10 – 96% customer satisfaction, 86% running installed base. Screen Shot 2017-06-05 at 11.39.12 PM.pngLaunch of iOS 11, Redesigned App drawers for messages app, integration with iCloud, End to end encryption. Apple Pay – Person to person payment also intrgarion with iMessage App. Apple Pay Card for holding your money. Siri – 375 million devices, Translation Beta. Camera – 1 Trillion photo per year. entrily new app store,Screen Shot 2017-06-05 at 11.38.07 PM.pngScreen Shot 2017-06-05 at 11.40.22 PM.png

    Introducing new ARKit for iOS.

    Screen Shot 2017-06-06 at 12.05.24 AM.png

  • iPad: 10.5 inch new iPad Pro with weight 1 pound, higher refresh rates, 40% faster graphics performance, multi touch, Files app for accessing all files with in the mac.Screen Shot 2017-06-06 at 12.17.13 AM.pngScreen Shot 2017-06-06 at 12.23.21 AM.png
  • Music: reinvent home music, Launch of HomePod, Musicologist. Screen Shot 2017-06-06 at 12.48.40 AM

Swift Code Snippets | Save Developer Hours

Do you write hundreds lines of code everyday ? And would you like to save ? Well than, code snippet libray may help you here.

The Concept of code snippets is saving a piece of code which we write very often. so now we can save it as snippet and use it quickly with shortcuts or drag & drop.

Here it is in IDE.

Screen Shot 2017-05-30 at 9.11.33 PM.png

How to build A Custom Snippet ?

By default, Xcode provides serval snippets and let add our own.

  1. Select the code which you want to create as snippet.
  2. Just drag and drop inside the Snippet option.

ima.png

we can also Edit Custom Snippet, Give the title and summary to our snippet, Completion Shortcut is what i like most its just give short name, define the scope, if its no longer required just select and delete it.