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!!!

Fundamentals Technique for Handling Peoples | Quick Notes

Handling people is one of the biggest deal, because different peoples different views so for making long lasting relationships in personal or professional we need to add few things. Today I was learning new book `How to win friends and influence people by ` so sharing quick note here.

Fundamentals Technique for Handling Peoples.

  1. Don’t Criticize or Complain

Human nature does not like to admit fault, when people are criticized they rarely response you well so never ever criticize or complain because it will never result in the behavior what we want.

  1. Give Honest Appreciation

when it comes to appreciation, it’s the powerful key to win heart. Honest appreciation brings out their best and it must be sincere, meaningful and with love.

  1. Listen to them

To get what we want from other people we have to first listen them careful and see things from the point of view of others. So if you are a better listener it will already solve lots of conflicts.

  1. Mutually Achievement

So follow the 3rd point and then we can combine our desires with their wants after that they will become eager to work with you, now you can mutually achieve out objectives.

Thank you for reading! If you really want to read more please share your feedback it will help a lot and it will be appreciated.

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.

Swift | No Main Method | No Entry Point | iOS App

That is interesting to see, there is no main() for Swift iOS project.

Because Cocoa Touch uses the @UIApplicationMain attribute (for Cocoa its @NSApplicationMain) to indicate that it is the application delegate, Using this attribute is equivalent to calling UIApplicationMain function and passing the class name of the delegate class.

If you do not use this attribute, than supply a main.swift file with code at top level that calls the UIApplicationMain(_:_:_:_:) it means if you app uses custom subclass of UIApplication as its principle class, call the UIApplicationMain(_:_:_:_:) function instead of using this attribute.

Objective C Days | Memory Management |Short Note to Brush up

Summary

Let’s see the traditional C ways for clearing up of unused objects is a bit of a nightmare. There are no ways in the language like how should be approached.

Imagine one function A create one object and pass it to another function B now both are using the same data now the problem is who is: the responsible for deleting it if it no longer used? and let’s say we have one function who is also gonna use the same data than what?

The solution is there are conventions and design patterns to handle these situations,  that’s the reason the reference counting was developed and management technique used in Obj-C.

What we have in Obj-C

Obj-C uses reference counting as its Memory Management Technique so according to that each object keeps an internal count of how many times it’s needed.  So only in case of, if count drops to zero. Yes you can compare it with Garbage Collector we have in Java but it’s not like automatic some chunk of code getting executed and removing the objects which ones are not needed.

Ownership

Most important thing is Object Ownership it means an object owner is someone that has explicitly said: “I need that object, don’t delete”. So one object can have more than one owner.

If object owner is not using it they have the responsibility to tell so that the reference count should be decreased by one. So while dealing with Obj-C pointers/Objects it’s really good to send correct messages.

Messages

alloc, it will allocate a fresh instance of the object, set the reference count +1.

new, shortest way to write alloc&init.

retain, you passed the object and you want to tell you to need that so its reference count should be increased by 1 again.

autorelease, need object temporarily and want to delete once you did with the operations.

copy creates a new copy of the object.

dealloc, opposite of init method, automatically get called right before the object is destroyed.

 Convenience Methods

Static methods used for allocating the initializing objects directly but are aware that you are not the owner of that object, once the scope of your program finish it will be removed.  Ex: [NSString stringWithFormat:@”Say %@”,@”Hello”];

Autorelease Pools

It’s an instance of NSAutoreleasePool, objects which are to be auto released. You can also send a message to autorelease or create object using convenience methods. So once the object added into autorelease pool and when the pool is popped, all the objects will be deleted.

Retain Cycles

Retain cycle is a condition where two objects strongly maintain a reference to each other and stop each other from being released. For example, let we have two classes as.

@interface Parent : NSObject
@property (nonatomic, strong) Child *child;
@end

@implementation Parent
@end

@interface Child : NSObject
@property (nonatomic, strong) Parent * parent;
@end

@implementation Child
@end

So, at some point of time when creating object of any of these class as

Parent *parent = [[Parent alloc] init];
Child *child = [[Child alloc] init];
parent.child = child;
child.parent = parent;

Here the parent object maintaining a strong reference of Child class and child object maintaining a strong reference of Parent class in back. So, both parent and child object having a reference count of one and one. Both objects will get released from memory only when their reference count will reach to zero but in this scenario, this will not be going to happen ever because both are mutually pointing to each other a dead lock is get created here. This situation is called the Retain Cycle that will lead to memory leaks.

Fortunately, it’s very easy to fix this problem—just tell one of the properties to maintain a weak reference to the other object so, what’s this weak and strong reference means??

Strong Reference: A strong reference says that don’t release this object till I m owning this.

Weak Reference: A weak reference says that don’t release this object until someone else pointing this strongly.

Just like strong and __strong, weak and __weak keywords are there for declaring properties and instance variables respectively as a weakly referenced object.

Quick Tips and common mistakes

Think about strong and weak pointers as well as retain cycles, Avoid unnecessary caching, Don’t declare every object  globally unnecessarily, use Xcode Instruments such as static analyzer and find the potential memory leaks and fix them

Arrays, Dictionaries and other objects that contain any object generally retain objects once you add it to them. It means once you create an object the reference count will be 1 and once you add it into an Arrays it will be 2.

Releasing the Object that you don’t own, let’s say if creating a new object using convenience method than there is no need to release that.

Keeping and using an Object that you don’t Own.

Calling dealloc directly. So never call dealloc by the way you have to call init after calling alloc its kinda default constructor for init the default value of the object.

Over-releasing. Accidentally you’re releasing something twice instead of once. You can also track these crashes by just enabling Zombies.

Retain Cycles. When an object released there is a cascading effect, the root object released its children’s as well and so on. Let’s say there is some condition like A owns B and B owns An as they own each other.