HTTP认证-摘要认证

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chenyongkai1/article/details/79012052

摘要认证 digest authentication   ← HTTP1.1提出的基本认证的替代方法

    服务器端以nonce进行质询,客户端以用户名,密码,nonceHTTP方法,请求的URI等信息为基础产生的response信息进行认证的方式。

     不包含密码的明文传递

    

    摘要认证步骤:

     1. 客户端访问一个受http摘要认证保护的资源。

     2. 服务器返回401状态以及nonce等信息,要求客户端进行认证。

HTTP/1.1 401 Unauthorized

WWW-Authenticate: Digest

realm="[email protected]",

qop="auth,auth-int",

nonce="dcd98b7102dd2f0e8b11d0f600bfb0c093",

opaque="5ccc069c403ebaf9f0171e9517f40e41"

     3. 客户端将以用户名,密码,nonce值,HTTP方法, 和被请求的URI为校验值基础而加密(默认为MD5算法)的摘要信息返回给服务器。

           认证必须的五个情报:

     ? realm : 响应中包含信息

     ? nonce  响应中包含信息

     ? username  用户名

     ? digest-uri  请求的URI

     ? response  以上面四个信息加上密码信息,使用MD5算法得出的字符串。


Authorization: Digest 

username="Mufasa",   客户端已知信息

realm="[email protected]",    服务器端质询响应信息

nonce="dcd98b7102dd2f0e8b11d0f600bfb0c093",  ← 服务器端质询响应信息

uri="/dir/index.html",  客户端已知信息

qop=auth,    服务器端质询响应信息

nc=00000001,  客户端计算出的信息

cnonce="0a4f113b",  客户端计算出的客户端nonce

response="6629fae49393a05397450978507c4ef1",  最终的摘要信息 ha3

opaque="5ccc069c403ebaf9f0171e9517f40e41"   服务器端质询响应信息

     4. 如果认证成功,则返回相应的资源。如果认证失败,则仍返回401状态,要求重新进行认证。


    特记事项:

     1. 避免将密码作为明文在网络上传递,相对提高了HTTP认证的安全性。

     2. 当用户为某个realm首次设置密码时,服务器保存的是以用户名,realm,密码为基础计算出的哈希值(ha1),而非密码本身。

     3. 如果qop=auth-int,在计算ha2时,除了包括HTTP方法,URI路径外,还包括请求实体主体,从而防止PUTPOST请求表示被人篡改。

     4. 但是因为nonce本身可以被用来进行摘要认证,所以也无法确保认证后传递过来的数据的安全性。


    nonce:随机字符串,每次返回401响应的时候都会返回一个不同的nonce 

    nounce:随机字符串,每个请求都得到一个不同的nounce 

       MD5(Message Digest algorithm 5,信息摘要算法)

          用户名:realm:密码  ha1

          HTTP请求方式:URI  ha2

          ha1:nonce:nc:cnonce:qop:ha2  ha3

以上摘自:http://blog.csdn.net/hotnet522/article/details/5824716


下面是代码:

-(void)initInterNetImageData:(NSString *)urlStr name:(NSString *)username password:(NSString *)password{

    

    NSLog(@"urlStr====%@",urlStr);

            NSURL *url1=[NSURLURLWithString:[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

            //自定义的request

            NSMutableURLRequest *request1 = [NSMutableURLRequestrequestWithURL:url1];

            //请求过期时间

            request1.timeoutInterval = 5;

            //get请求

            request1.HTTPMethod = @"GET";

            

            NSURLSession * session1=[NSURLSessionsharedSession];

            [[session1 dataTaskWithRequest:request1completionHandler:^(NSData *_Nullable data, NSURLResponse *_Nullable response, NSError * _Nullable error) {

                NSHTTPURLResponse * Hresponse1=(NSHTTPURLResponse *)response;

                NSLog(@"response=======%@",Hresponse1);

                if (Hresponse.statusCode==401) {

                    NSArray * UrlArr=[urlStr componentsSeparatedByString:@"/"];

                    NSMutableString * urlStr2=[[NSMutableStringalloc]init];

                    if ([UrlArr isKindOfClass:[NSArrayclass]]) {

                        for (int i=3; i<UrlArr.count; i++) {

                            

                            [urlStr2 appendFormat:@"/%@",UrlArr[i]];

                            

                        }

                    }


                    NSString * autho=[selfhandle401Code:Hresponse1 url2:urlStr2 user:username pass:password];

                    

                    NSMutableURLRequest *request2 = [[NSMutableURLRequestalloc]initWithURL:url];

                    request2.timeoutInterval=5;

                    [request2 addValue:autho forHTTPHeaderField:@"Authorization"];

                    [request2 setHTTPMethod:@"GET"];

                    

                    NSURLSession * session2=[NSURLSessionsharedSession];

                    [[session2 dataTaskWithRequest:request2completionHandler:^(NSData *_Nullable data, NSURLResponse *_Nullable response, NSError * _Nullable error) {

                        NSHTTPURLResponse * Hresponse2=(NSHTTPURLResponse *)response;

                        if (data.length>100) {

                            NSString *URLResult = [Hresponse2.URLabsoluteString];

                            NSLog(@"URLResult=======%@",URLResult);

                            [self chaxun:URLResult data:data];

                        }

                    }]resume];

                    

                }

                

            }] resume] ;


    

}



-(NSString *)handle401Code:(NSHTTPURLResponse *)response url2:(NSString *)url2 user:(NSString *)username pass:(NSString *)password

{


    NSString *wwwAuthenticate = [[response allHeaderFields ]objectForKey:@"Www-Authenticate"];

    NSString *realm = nil;

    NSString *qop = nil;

    NSString*nonce = nil;

    NSString *opaque = nil;

    //解析wwwAuthenticate

    NSArray *arr = [wwwAuthenticate componentsSeparatedByString:@","];

    for (NSString *perStr in arr) {

        NSRange range= [perStr rangeOfString:@"="];

        //提取=后面的

        NSString *perStrFirst = [perStr substringToIndex:range.location];

        NSString *perStrSecond =[perStr substringWithRange:NSMakeRange(range.location+range.length+1,perStr.length-range.location-range.length-2)];

        if ([perStrFirst rangeOfString:@"realm"].location !=NSNotFound) {

            realm = perStrSecond;

            NSLog(@"realm = %@",realm);

        }

        if ([perStrFirst rangeOfString:@"qop"].location !=NSNotFound) {

            qop = perStrSecond;

            NSLog(@"qop = %@",qop);

        }

        if ([perStrFirst rangeOfString:@"nonce"].location !=NSNotFound) {

            nonce=perStrSecond;

            NSLog(@"nonce = %@",nonce);

        }

        if ([perStrFirst rangeOfString:@"opaque"].location !=NSNotFound) {

            opaque=perStrSecond;

            NSLog(@"opaque = %@",opaque);

        }

        

    }

    

    // 以从1970年到现在时间差作为branch的值

    NSTimeInterval time = [[NSDatedate]timeIntervalSince1970];

    long long int t = (long long int)time;

    NSString *cnonce = [[NSStringalloc]initWithFormat:@"%lld%d",t,arc4random()+10000];

    

    static unsigned int ncCnt = 1;

    NSString *nc = [[NSStringalloc]initWithFormat:@"%d",++ncCnt];

    

    NSString *algorithm = @"MD5";

    

    NSString *uri = url2;

    

    NSString *method = @"GET";

    

    NSString *md5First = [[NSStringalloc]initWithFormat:@"%@:%@:%@",username,realm,password];

    NSString * ha1=[md5First MD5Digest];

    

    NSString *md5Second = [[NSStringalloc]initWithFormat:@"%@:%@",method,uri];

    NSString * ha2=[md5Second MD5Digest];

    

    NSString *responseStr = [[NSStringalloc]initWithFormat:@"%@:%@:%@:%@:%@:%@",ha1,nonce,nc,cnonce,qop,ha2];

    

    NSString *ha3 = [responseStr MD5Digest];

    NSString *authorization = nil;

    if (opaque != nil) {

        authorization = [[NSStringalloc]initWithFormat:@"Digest username=\"%@\",realm=\"%@\",nonce=\"%@\",uri=\"%@\",response=\"%@\", opaque=\"%@\",qop=%@,nc=\"%@\",cnonce=\"%@\",algorithm=\"%@\"",@"admin",realm,nonce,uri,ha3,opaque,qop,nc,cnonce,algorithm];

        

    }else{

        authorization = [[NSStringalloc]initWithFormat:@"Digest username=\"%@\",realm=\"%@\",nonce=\"%@\",uri=\"%@\",response=\"%@\", qop=\"%@\",nc=\"00000001\",cnonce=\"%@\",algorithm=\"%@\"",@"admin",realm,nonce,uri,ha3,qop,cnonce,algorithm];

    }

    

    NSLog(@"authorization=========%@",authorization);

    

    return authorization;

}



#import <CommonCrypto/CommonDigest.h>

#import "NSString+MD5.h"


@implementation NSString (MD5)


- (NSString *)MD5Digest

{

    const char* input = [self UTF8String];

    unsigned char result[CC_MD5_DIGEST_LENGTH];

    CC_MD5(input, (CC_LONG)strlen(input), result);

    

    NSMutableString *digest = [NSMutableStringstringWithCapacity:CC_MD5_DIGEST_LENGTH *2];

    for (NSInteger i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {

        [digest appendFormat:@"%02x", result[i]];

    }

    

    return digest;

}


个人遇到的问题总结:

1.-(NSString *)handle401Code:(NSHTTPURLResponse *)response url2:(NSString *)url2 user:(NSString *)username pass:(NSString *)password


猜你喜欢

转载自blog.csdn.net/chenyongkai1/article/details/79012052