ios开发使用Basic Auth 认证方式

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发送,如下面代码:

  

  1. //http的get请求地址  
  2.    NSString *urlStr=[NSString stringWithFormat:@"https://192.168.1.157:8443/v1/sms/send/%@",self.username.text];  
  3.    NSURL *url = [NSURL URLWithString:urlStr];  
  4.    //自定义的request  
  5.    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];  
  6.    //请求过期时间  
  7.    request.timeoutInterval = 10;  
  8.    //get请求  
  9.    request.HTTPMethod = @"GET";  
  10.    //配置用户名 密码  
  11.    NSString * str = [NSString stringWithFormat:@"%@:%@",@"lairen.com",@"sdclean.com"];  
  12.    //进行加密  [str base64EncodedString]使用开源Base64.h分类文件加密  
  13.    NSString * str2 = [NSString stringWithFormat:@"Basic %@",[str base64EncodedString]];  
  14.    [request setValue:str2 forHTTPHeaderField:@"Authorization"];  
  15.    AFHTTPRequestOperation *op=[[AFHTTPRequestOperation alloc]initWithRequest:request];  
  16.    //设置返回数据为json数据  
  17.    op.responseSerializer= [AFJSONResponseSerializer serializer];  
  18.    //发送网络请求  
  19.    [op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {  
  20.          
  21.        NSLog(@"%@",responseObject);  
  22.    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {  
  23.         NSLog(@"%@",error);  
  24.    }];  
  25.    //请求完毕回到主线程  
  26.    [[NSOperationQueue mainQueue] addOperation:op];  

     使用Basic Auth认证方式,AFN发送网络请求就是上述代码的格式,其中代码的一些难懂的点,我在下图做了注释;

      我注释的第一个是用户名,第二个是密码,这个使我们Basic Auth认证方式必须设置的请求头,然后第三个呢是我们为了我确保安全把用户名和密码的字符串进行了Base64加密,使用的2个文件是开源的Base64.h  Base64.m 。github上面就可以下载。

  上述代码中的这行是对字符串进行的加密,记住是使用的Base64.h分类方法进行的加密,一定要先导入Base64.h文件才可以这样加密。

  1. [str base64EncodedString]  
  1. NSString * str2 = [NSString stringWithFormat:@"Basic %@",[str base64EncodedString]];  

  到这里我们的Basic Auth认证方式就讲完了,怎么样,很简单吧。

 
原文地址:https://www.cnblogs.com/itlover2013/p/4842869.html