Search code examples
iosobjective-cafnetworking-2basic-authentication

Basic auth header from username and password is not working In AFNetworking 2.0


I am invoking A API its required Authorisation header.

this is API need on given URL

username : [email protected]

password : testingyouonit2

to create the Authorisation header

step 1 - do a base64 encoding of the given password.

step 2 - do a SHA256 hash on the password obtained in step 1

step 3 - use the password obtained in step 2 and given username to create the authorization header

Now i am passing request using AFNetworking

NSString *email=@"[email protected]";
NSString *password=[self encodeStringTo64:@"testingyouonit2"];

Here i encoded my password

- (NSString*)encodeStringTo64:(NSString*)fromString
{
    NSData *plainData = [fromString dataUsingEncoding:NSUTF8StringEncoding];
    NSString *base64String;
    if ([plainData respondsToSelector:@selector(base64EncodedStringWithOptions:)]) {
        base64String = [plainData base64EncodedStringWithOptions:kNilOptions];
    } else {
        base64String = [plainData base64Encoding];
    } 

    return base64String; 
}

Now i am passing GET Request

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];

    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    [manager.requestSerializer setAuthorizationHeaderFieldWithUsername:email password:password];
    [manager.requestSerializer setValue:@"CAS256" forHTTPHeaderField:@"Authorization"];


    [manager GET:@"https://myurlhere/youit" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"JSON: %@", responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
    }];

Now each time i am getting this

Error: Error Domain=com.alamofire.error.serialization.response Code=-1011 "Request failed: bad request (400)" UserInfo=0x7c361610 {com.alamofire.serialization.response.error.response=<NSHTTPURLResponse: 0x7aed9220> { URL: https://myurlhere/youit } { status code: 400, headers {
    "Access-Control-Allow-Origin" = "*";
    Connection = "keep-alive";
    "Content-Length" = 114;
    "Content-Type" = "application/json";
    Date = "Sat, 11 Jul 2015 02:56:46 GMT";
    Server = "nginx/1.1.19";
} }, NSErrorFailingURLKey=https://myurlhere/youit, NSLocalizedDescription=Request failed: bad request (400), com.alamofire.serialization.response.error.data=<7b0a2020 22657272 6f725f63 6f646522 3a202269 6e76616c 69645f61 7574685f 68656164 6572222c 0a202022 6d657373 61676522 3a202249 6e76616c 69642061 7574686f 72697a61 74696f6e 2e205573 6520616e 20617574 68206865 61646572 206f7220 61636365 73732068 61736822 0a7d>}

where is the mistake i am doing to make basic Auth


Solution

  • Lets create SHA256 and pass it password and try it

    NSString *email=@"[email protected]";
    NSString *password=[self encodeStringTo64:@"testingyouonit2"];
    

    add one more method to generate a Sha256 password and pass in to request

    Step-1 using this method you need to #include <CommonCrypto/CommonDigest.h>

    -(NSString*)sha256HashFor:(NSString*)input
    {
        const char* str = [input UTF8String];
        unsigned char result[CC_SHA256_DIGEST_LENGTH];
        CC_SHA256(str, strlen(str), result);
    
        NSMutableString *ret = [NSMutableString stringWithCapacity:CC_SHA256_DIGEST_LENGTH*2];
        for(int i = 0; i<CC_SHA256_DIGEST_LENGTH; i++)
        {
            [ret appendFormat:@"%02x",result[i]];
        }
        return ret;
    }
    

    and call this
    Note : pass here encoded password you used

    NSString *password=[self encodeStringTo64:@"testingyouonit2"];
     `password=[self sha256HashFor: password];`
    

    and final step

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        manager.responseSerializer = [AFJSONResponseSerializer serializer];
    
        [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
        [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
        manager.requestSerializer = [AFJSONRequestSerializer serializer];
        manager.requestSerializer = [AFHTTPRequestSerializer serializer];
        [manager.requestSerializer setAuthorizationHeaderFieldWithUsername:email password:password];
    
    
    
        [manager GET:@"https://myurlhere/youit" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSLog(@"JSON: %@", responseObject);
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"Error: %@", error);
        }];
    

    let me see the result