Showing posts with label authentication. Show all posts
Showing posts with label authentication. Show all posts

Thursday, May 12, 2016

Objective C Authentication Challenges

We frequently call web services in our applications. Servers throw different types of authentication challenges based on the authentication methods with which they were designed for security purposes.

Here are the different types of authentication challenges.

  • NSURLAuthenticationMethodDefault;
  • NSURLAuthenticationMethodHTTPBasic;
  • NSURLAuthenticationMethodHTTPDigest;
  • NSURLAuthenticationMethodHTMLForm;
  • NSURLAuthenticationMethodNTLM 
  • NSURLAuthenticationMethodNegotiate 
  • NSURLAuthenticationMethodServerTrust




                         


We need to handle them in the authentication challenge delegate methods by checking the challenge type. Not every time we get the user's authentication challenge.

In this post, Let's see how to handle NSURLAuthenticationMethodNTLM and NSURLAuthenticationMethodServerTrust handling in NSURLSession's didReceiveChallenge delegate method.

NSURLAuthenticationMethodServerTrust


We will get this Authentication method, When we are hitting a HTTPS server.



-(void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(    NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler
{
    
    if ([challenge.protectionSpace.authenticationMethod isEqualToString:
                        NSURLAuthenticationMethodServerTrust]) {   //Server trust challenge
        
        NSURLCredential *credential =     
                        [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
                            [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
        
    }
}




As shown in the above code, Check every time the type of challenge, I mean the type the Authentication challenge we are getting as delegate call back and respond to that challenge 
accordingly.

NSURLAuthenticationMethodNTLM:



If the server we are hitting is having NTLM authentication configured, We need to pass the logged In user's credentials in the challenge delegate method.



-(void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(    NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler

{
    
    if ([challenge.protectionSpace.authenticationMethod isEqualToString:    
                          NSURLAuthenticationMethodServerTrust]) {   //Server trust challenge
        
        NSURLCredential *credential = 
                           [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];

        [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
        
    }
    
    else{  //NTLM authentication challenge
    
            NSString *userName = @"username";
            NSString *pwd =  @"password";
            
            if ([challenge previousFailureCount] == 0) {
      
                    
                    NSURLCredential *cred = 
                                   [NSURLCredential credentialWithUser:userName password:pwd 
                                                         persistence:NSURLCredentialPersistenceNone];

                    completionHandler(NSURLSessionAuthChallengeUseCredential, cred);
                
                
            }
            
            else {
     
                   completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
            }
        
    }


}



That's how we need to check the challenge type and respond accordingly.



                         


Hope this post is useful. Feel free to comment in case of any queries.

Wednesday, May 11, 2016

Objective C Basic Authentication Challenge (NSURLAuthenticationMethodHTTPBasic)

If we get authentication challenge as NSURLAuthenticationMethodHTTPBasic in your  authentication challenge delegate method using NSURLConnection/NSURLSession, We need to pass the credentials in the 'Autherization' header field of the request.

Here is the objective C code to convert the user credentials to BASIC format.
      

   NSString *username = @"username";
   NSString *password = @"password";

   NSString *authStr = [NSString stringWithFormat:@"%@:%@", username, password];

   NSData *authData = [authStr dataUsingEncoding:NSASCIIStringEncoding];

   NSString *authValue = [authData base64EncodedStringWithOptions:0];

   [request setValue:[NSString stringWithFormat:@"Basic %@",authValue]  
                                                            forHTTPHeaderField:@"Authorization"];
      



                         


If you look at the code, It's a 4 step process.

  1. We need to place the colon in between username and password.
  2. Convert the above resulted string to data using ASCII Encoding.
  3. Convert the above resulted data into string using Base64 Encoding.
  4. Finally, Add Basic as a prefix to the above resulted string with a space in between.



                         


Hope this post is useful. Feel free to comment incase of any queries.

Sunday, January 10, 2016

Objective C SharePoint Authentication Mode

SharePoint supports different types of authentication which we can set up in the server.
In my SharePoint Login service post, I have explained the process of login to SharePoint using the Windows authentication (BASIC authentication).

What if SharePoint is having "Forms" authentication?

Getting confused of these? What is this Windows and what is this Forms authentication and all?



                         


I am going to clear these things in a while in this post.

Before getting connected to any SharePoint sever it is a good practice to check the mode of authentication that server is having. As we know the SOAP services are a way to get connected to SharePoint and play with it's content and permissions, Let's have a look at fetching the authentication mode of a SharePoint server that we are trying to get connected.

Here it is:

SOAP BODY





SOAP ACTION

http://schemas.microsoft.com/sharepoint/soap/Mode

END POINT

_vti_bin/authentication.asmx

Here, I have mentioned only the necessary things to call the SOAP service. Hope I don't need to place the piece of code for calling the service and all. We are all Objective C experts and we know how to do it. Isn't it :)

Let's have a look at the response that the above SOAP service throws.


SOAP RESPONSE:









If you look at the ModeResult, the authentication mode here is "Forms". It throws "Windows" for windows based authentication.

So based on this response we need to change the login process to SharePoint.
In a way, it is just changing the passing of user credentials to all the SharePoint services.

Happy Login :)


                         



Hope this post is useful.

Friday, August 21, 2015

Objective c SharePoint content fetch soap service

Hope whoever reading this article is familiar with SharePoint authentication using Objective c. If not checkout my post on Objective c SharePoint login service , to get better idea on connecting and getting authenticated to SharePoint Server.

Now, we are able to successfully get authenticated to the SharePoint. So, what's next? Obviously 'Fetching Content' from the SharePoint to display it in our application or for some other purpose. After that you may need operations like listed below.


  •  Create Folder
  •  Upload File
  •  Rename Content
  •  Tagging Files


Let's start with content fetching from the SharePoint. Unlike other CMS systems (like BOX, DropBOX), SharePoint have a structure called 'List'. A List is nothing but a start point where after creating that you can create/upload folders and files. To get better idea on List structure of SharePoint, please go through the SharePoint List structure documentation in Microsoft SharePoint official website.

SharePoint gives you SOAP services for all the operations like I have mentioned above that we need to do on our SharePoint content. This msdn link has the list of end points and soap services names and descriptions that SharePoint provides. As shown in that link the endpoint for getting list of SharePoint items is _vti_bin/lists.asmx. At this location you can see the request and response of the SharePoint SOAP service for GetListItems. GetListItems is the service that we are going to use to get List content from the SharePoint.

Let's have a look at the SOAP service in objective c for fetching list content.




This is the SOAP body that we need to pass at the time of service request. This type of xml SOAP body might be familiar to the developers who have an experience on consuming SOAP services. I am really sorry for putting the code as an image. I tried to copy paste my code but, this xml was colliding with my article html. Once I get a solution for this, I will definitely place the raw code so that If any one need it, they can directly copy paste the code.

Let's see this body in detail and you might have observed that I have used Objective c string placeholders(%@) in this body. First one is for the SharePoint list name. This List is the one on whose content we are interested about in our iOS application and for that only we have connected to SharePoint. The second placeholder is for the folder in that list we are interested about if we are. Here we need to talk about what is folder as we have already given list name, whose content we wanted to fetch. As I said List is the staring point of the directory structurte, where we can have our folders and files. All the time we don't need to fetch the entire list content. Some times we may just need content of one particular folder. In this case we need to mention the folder that we are interested.

Let's see some examples for list names and folder path that we need to parse from the SharePoint URL given to us as these two parameters are very important for the SOAP body.

Example Link - 1:


https://mydomain.com/test/examplelist/Forms/AllItems.aspx?RootFolder=/test/examplelist/fol1/fol2
This is a typical SharePont link structure. All the SharePoint basic urls end with Forms/AllItems.aspx. Here 'examplelist' which is just before the Forms can be taken as the list name that the url is pointing to. 'examplelist' is the list name that we need to put in the SOAP body. The RootFolder parameter of the url tells us the folder in the 'examplelist' List, that we are interested about. So 'fol2' is the target folder name. If you can observe it is at the second level in the list as it is inside of another folder called 'fol1'.
So in this case as the list name and folder values are as shown below.




Example Link - 2:


https://mydomain.com/test/examplelist/Forms/AllItems.aspx?           

In this url there is no RootFolder parameter. It means we are interested directly on the 'examplelist' list content. In this case it's obvious that the folder parameter will be empty. So in this case as the list name and folder values are as shown below.





Example Link - 3:


https://mydomain.com/test/examplelist/Forms/AllItems.aspx?RootFolder=/test/examplelist/fol1     

This example url is same as the url in the Example-1. The only difference is that target folder is at the root level of the examplelist list. 
So in this case as the list name and folder values are as shown below.






Hope now you have got complete picture on the two important values that we have to put in the GetListItems SOAP body(listname and Folder). The next important is the 'rowLimit' value. Let's see what this is. If we have so many folders/files (say around 2000) in our target list or folder whose content we are fetching, Obviously it's a bad practice to fetch all the content and display in the application. So, What we need here is called pagination. This 'rowLimit' parameter helps us for this pagination functionality. If you put 100 as the value, It will give you the 100 rows, means the first 100 assets in the root folder or in the root list. There is an option for querying the items in the target folder or list, which is not that important at this point of time as our mail goal is to first fetch the content.

Now, we understood how to call GetListItems SOAP service of SharePoint to fetch content. It's time to know about the response it throws. 

SharePoint GetListItems service throws a bunch of the below shown xml objects which are nothing but the folders and files in your SharePoint targeted list or folder. In this you can see the folder/file name, author, modified date etc....




Hope this article is useful to SharePoint newbies.


Fell free to comment in case of any queries/concerns.

Thursday, August 20, 2015

Objective c SharePoint login service

If you are trying to connect to SharePoint from an iOS application using Objective c, this article is for you. Unfortunately there is no enough information on the web regarding SharePoint connection from an iOS application using Objective c. Where as you can find well enough and better tutorials for an .Net application because, both are from same giant organisation like Microsoft. 

So it's easy for an .Net developer to quick start integrating SharePoint CMS in their .Net application. But, for an iOS developer it's a night mare. All we have is SharePoint SOAP services to communicate with the SharePoint.

Though, we are having REST services to connect to SharePoint, I am not supposed to talk about those because I don't have any experience on that. Here, I am going to give a quick start to connect to SharePoint. I mean first in place to get authenticated to SharePoint.

In SharePoint you can set different authentication mechanisms in the sever settings. Here I am going to show you a sample code to get connected to a SharePoint which is having BASIC authentication mechanism.

Let's talk about BASIC authentication first. If the SharePoint that you are trying to connect to is having a BASIC authentication mechanism in the server settings, You have to encode the user credentials while passing it to the server through a service for authentication.



                         




Here is the Objective c sample code to convert user credentials for BASIC authentication. 


    NSString *authStr = [NSString stringWithFormat:@"%@:%@", username, password];
    NSData *authData = [authStr dataUsingEncoding:NSASCIIStringEncoding];
    NSString *authValue = [authData base64EncodedStringWithOptions:0];

What I am doing in the above code is, I am taking username and password to a string with the separator as colon(:). Then I am doing the ASCII encoding of the string to convert it to
NSData. Finally I am doing base64 encoding and generating a BASIC authentication string of user credentials.

Here is the code to get user authentication to SharePoint. 


NSError *error = nil;
NSURLResponse *response;
            
NSURL *authenticationlURL = [NSURL URLWithString:[[NSUserDefaults standardUserDefaults] 
                                                             objectForKey:@"SP_AUTHENTICATION_URL"]];            
            
            
NSString *authStr = [NSString stringWithFormat:@"%@:%@", username, password];
NSData *authData = [authStr dataUsingEncoding:NSASCIIStringEncoding];
NSString *authValue = [authData base64EncodedStringWithOptions:0];

NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setURL:authenticationlURL];
[request setValue:[NSString stringWithFormat:@"Basic %@",authValue] 
                                                                  forHTTPHeaderField:@"Authorization"];
[request setTimeoutInterval:60];
            
NSData *responseData = [NSURLConnection sendSynchronousRequest:request 
                                                  returningResponse:&response error:&error];

I am using normal NURLConnection class sendSynchronousRequest method only. I am giving the url as SharePoint base URL. We need to pass the 'Autherization' header with the value of the BASIC authentication string that we have generated.

That's all in coding. All you have to check is whether the status code of the response is coming as 200 or not to know whether the authentication is success or not. The response gives you some other values also. But at this point we don't need to worry about those values. If the status code is 200, it's like authentication is successful.

Hope this article is helpful to newbies to SharePoint.

Feel free to comment in case of any queries or comments.