Objective C: Basic HTTP Authorization


  1.  First version of "Authorization":
    NSString *loginString = [NSString stringWithFormat:@"%@:%@", [self userName], [self password]];
    NSString *encodedLoginData = [Base64 encode:[loginString dataUsingEncoding:NSUTF8StringEncoding]];  
    NSString *base64LoginData = [NSString stringWithFormat:@"Basic %@",encodedLoginData];
    
    NSURL *url=[NSURL URLWithString:@"http://my_url.com"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
                    timeoutInterval:10.0];
    
    [request setHTTPMethod:@"POST"];
    
    [request setValue:base64LoginData forHTTPHeaderField:@"Authorization"];
    
    NSURLConnection *urlConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    
  2. Second version of "Authorization":
    NSURL *URL = [NSURL URLWithString:url];
    NSURLRequest *request = [NSURLRequest requestWithURL:URL
                                             cachePolicy:NSURLRequestUseProtocolCachePolicy
                                         timeoutInterval:10.0];
    
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    
    NSURLConnection Delegates
    - (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
        if ([challenge previousFailureCount] == 0) {
            NSLog(@"received authentication challenge");
            NSURLCredential *newCredential = [NSURLCredential credentialWithUser:@"USER"
                                                                        password:@"PASSWORD"
                                                                     persistence:NSURLCredentialPersistenceForSession];
            NSLog(@"credential created");
            [[challenge sender] useCredential:newCredential forAuthenticationChallenge:challenge];
            NSLog(@"responded to authentication challenge");    
        }
        else {
            NSLog(@"previous authentication failure");
        }
    }
    

No comments:

Post a Comment