AFNetworking credential download task (HTTP Basic Auth)

I need to upload video files from my application to the server. I tried to do this via [AFHTTPRequestOperationManager post:parameters:success:failure] , but unfortunately continued to receive request timeouts. Now I'm trying something similar to creating a loading task from AF Docs .

I read on SO and Docs about setSessionDidReceiveAuthenticationChallengeBlock: and tried to implement the entire malarky download as follows:

 __block ApiManager *myself = self; // Construct the URL NSString *strUrl = [NSString stringWithFormat:@"%@/%@", defaultUrl, [self getPathForEndpoint:endpoint]]; NSURL *URL = [NSURL URLWithString:strUrl]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL]; [request setHTTPMethod:@"POST"]; // Build a session manager NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration]; // Set authentication handler [manager setSessionDidReceiveAuthenticationChallengeBlock:^NSURLSessionAuthChallengeDisposition(NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential *__autoreleasing *credential) { *credential = myself.credentials; return NSURLSessionAuthChallengeUseCredential; }]; // Create the upload task NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:filePath progress:nil completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { if (error) { [myself endpoint:endpoint returnedFailure:error]; } else { [myself endpoint:endpoint returnedSuccess:responseObject]; } }]; // and run with it [uploadTask resume]; 

The myself.credentials object was set earlier to have the correct username and password. Whenever this request fires, I get 401 unauthorised as an answer. I tried putting NSLog(@"CHALLENGE") inside the task block above, but it never seems called, so AFNetworking does not give me a way to provide credentials. I know this works fine on the server side because I tested it with Postman.

How can I get AFNetworking to provide me credentials for HTTP Basic Auth with this download task?

+6
source share
1 answer

I'm not sure about AFNetworking setSessionDidReceiveAuthenticationChallengeBlock , but as long as you have NSMutableURLRequest , you can configure the HTTP authorization header directly on the request object:

[request setValue:base64AuthorizationString forHTTPHeaderField:@"Authorization"];

Keep in mind that the value must be the base representation of the username:password string.

Otherwise for GET, POST requests, etc. in the session manager, you can set credentials in the query serializer used by the session manager. Cm:

[AFHTTPRequestSerializer setAuthorizationHeaderFieldWithUsername:password:] [AFHTTPRequestSerializer clearAuthorizationHeader]

0
source

Source: https://habr.com/ru/post/976021/


All Articles