http://blog.csdn.net/joonchen111/article/details/48447813
 
         我们app的开发通常有2种认证方式   一种是Basic Auth,一种是OAuth;现在普遍还是使用OAuth的多,而使用Basic Auth认证的少,正好呢我今天给大家介绍的就是使用的比较少的Badic Auth认证方式,这种认证方式开发和调试简单, 没有复杂的页面跳转逻辑和交互过程,更利于发起方控制。然而缺点就是安全性更低,不过也没事,我们可以使用https安全加密协议,这样才更安全。
        我使用的是AFNetworking发送的网络请求,因此我们用Basic Auth认证方式就不能再使用AFN的默认的GET或者POST请求,而是自己定义的NSMutableRequest请求,使用AFN发送,如下面代码:
  
-    NSString *urlStr=[NSString stringWithFormat:@"https://192.168.1.157:8443/v1/sms/send/%@",self.username.text];  
-    NSURL *url = [NSURL URLWithString:urlStr];  
-    
-    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];  
-    
-    request.timeoutInterval = 10;  
-    
-    request.HTTPMethod = @"GET";  
-    
-    NSString * str = [NSString stringWithFormat:@"%@:%@",@"lairen.com",@"sdclean.com"];  
-    
-    NSString * str2 = [NSString stringWithFormat:@"Basic %@",[str base64EncodedString]];  
-    [request setValue:str2 forHTTPHeaderField:@"Authorization"];  
-    AFHTTPRequestOperation *op=[[AFHTTPRequestOperation alloc]initWithRequest:request];  
-    
-    op.responseSerializer= [AFJSONResponseSerializer serializer];  
-    
-    [op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {  
-          
-        NSLog(@"%@",responseObject);  
-    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {  
-         NSLog(@"%@",error);  
-    }];  
-    
-    [[NSOperationQueue mainQueue] addOperation:op];  
 
     使用Basic Auth认证方式,AFN发送网络请求就是上述代码的格式,其中代码的一些难懂的点,我在下图做了注释;
 

      我注释的第一个是用户名,第二个是密码,这个使我们Basic Auth认证方式必须设置的请求头,然后第三个呢是我们为了我确保安全把用户名和密码的字符串进行了Base64加密,使用的2个文件是开源的Base64.h  Base64.m 。github上面就可以下载。
  上述代码中的这行是对字符串进行的加密,记住是使用的Base64.h分类方法进行的加密,一定要先导入Base64.h文件才可以这样加密。
 
- [str base64EncodedString]  
 
 
 
- NSString * str2 = [NSString stringWithFormat:@"Basic %@",[str base64EncodedString]];  
 

 
  到这里我们的Basic Auth认证方式就讲完了,怎么样,很简单吧。
 
ios开发使用Basic Auth 认证方式
原文:http://www.cnblogs.com/itlover2013/p/4842869.html