Basic authorization in NSMutableURLRequest isn't working - objective-c

I'm trying to add basic authorization to my request header. The code below compiles and I dont get any runtime errors. However, on the server side I do not see the "Authorization" in the header at all.
I was able to implement the didReceiveAuthenticationChallenge method and that works, but I dont understand why I have to do it this way. I simply want to always add basic auth to every request.
I'm not interested in using ASIHTTPRequest.
Thanks for the help!
This is my code below:
NSURL *url = [[NSURL alloc] initWithString:#"http://localhost:8000/MyWebService"];
self.userName = #"myusername";
self.password = #"mypassword";
NSMutableString *credentials = [[NSMutableString alloc] initWithFormat:#"%#:%#", userName, password];
NSString *encodedCredentials = [[credentials dataUsingEncoding:NSUTF8StringEncoding] base64EncodedString];
NSString *authHeader = [NSString stringWithFormat:#"Basic %#", encodedCredentials];
NSMutableURLRequest* req = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:5];
[req addValue:authHeader forHTTPHeaderField:#"Authorization"];
self.urlConnection = [[NSURLConnection alloc] initWithRequest:req delegate:self startImmediately:YES];
if (self.urlConnection) {
self.receivedData = [NSMutableData data];
}
else {
errorLabel.text = #"Error connecting to the server";
}

The didReceiveAuthenticationChallenge is the way it works in iOS and the easiest way to do it. It will be submitted with every request (with the challenge). Guess that's not what you want to hear=)
I guess you have tried using different tutorials. I've used this one to authenticate before:
Basic access Auth, iOS

Related

AccessToken is not valid error : iOS Obj C

I am developing an iOS application in objective C where when a user logins to the App, it will return an access token in son format. I need to query other server api with the access token. My son response is like :
{
accessToken = "$2a$10$6Tu7e.fsKQxp4cw/SkRBS.65wsA.Pagt2EwdpBjXRdaUQb6yNxTtS";
id = 12;
message = "login successful";
success = 1;
}
I am retrieving this via
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
[jsonDict valueForKey:#"accessToken"];
Whenever i try with the accessToken get from this, it shows invalid access token.(I use the same access token in postman.and got the same response).
When I copy the access token from postman and use the same in iOs code, it works fine. What is happening? Any help will be appreciated.
The code I am using to call the http request is:
// NSString *accessToken = [[NSUserDefaults standardUserDefaults] valueForKey:#"accessToken"];
//Send JSON data to cloud using HTTP POST
NSURL *url1 = [NSURL URLWithString:urlString];
NSMutableURLRequest *request1 = [NSMutableURLRequest requestWithURL:url1
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request1 setHTTPMethod:#"GET"];
// [request1 setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request1 setValue:accessToken forHTTPHeaderField:#"Authorization"];
NSLog(#"access :: %#",accessToken);
NSURLConnection *conn1 = [[NSURLConnection alloc] initWithRequest:request1 delegate:self];

oAuth2 retrieve profile email in iOS7

I followed this tutorial and was able to authenticate successfully and got the access token, now I am struggling to understand how can I get email associated with user profile before closing webview and join back my controller.
Any suggestions? I understand that Google has SDK for this, but I don't want to go that route if my requirement is possible with the tutorial I am using.
if (verifier) {
NSString *data = [NSString stringWithFormat:#"code=%#&client_id=%#&client_secret=%#&redirect_uri=%#&grant_type=authorization_code", verifier,client_id,secret,callbakc];
NSString *url = [NSString stringWithFormat:#"https://accounts.google.com/o/oauth2/token"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[data dataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
receivedData = [[NSMutableData alloc] init];
} else {
// ERROR!
}
//Should I need to call another HTTP to retrieve email (or) email already available part of any other response?
If I need to call another HTTP, what URL should be invoked?
Make an authenticated request to the people.get API method with the userId set to me. The person resource has an emails array and the email with type set to account is their verified email.

AFNetworking upload task with credentials (HTTP Basic Auth)

I need to upload video files from my app to a server. I tried doing so via [AFHTTPRequestOperationManager post:parameters:success:failure] but unfortunately kept getting request timeouts. I'm now trying something similar to Creating an Upload Task from the AF Docs.
I read on SO and the AF Docs about setSessionDidReceiveAuthenticationChallengeBlock: and tried to implement the whole upload malarky 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 has been set previously to have the correct username and password. Whenever this request fires, I get 401 unauthorised as a response. I tried putting NSLog(#"CHALLENGE") inside the challenge block above, but it never seems to get called, so AFNetworking isn't giving me a way to supply credentials. I know that this works perfectly well on the server side because I've tested it with Postman.
How can I get AFNetworking to let me supply credentials for HTTP Basic Auth with this upload task?
I'm not sure about AFNetworking's setSessionDidReceiveAuthenticationChallengeBlock, but as long as you have an NSMutableURLRequest you may set the Authorization HTTP Header directly on the request object:
[request setValue:base64AuthorizationString forHTTPHeaderField:#"Authorization"];
Keep in mind that the value must be base64 representation of the username:password string.
Otherwise, for GET, POST, etc. requests on a session manager, you may set the credentials on the request serializer used by the session manager. See:
[AFHTTPRequestSerializer setAuthorizationHeaderFieldWithUsername:password:]
[AFHTTPRequestSerializer clearAuthorizationHeader]

IOS Application to send data to a Rest API service

I want to create an iPhone application to send data to a Rest API service. If the data is a string defined as geoX#35#geoY#65 which NSS method shall i use. Was thinking of NSString and NSMutablerequest to make my request and define my string but this isn't working atm.Also i am using NSURLconnection to establish a connection with the server(maybe that's faulty too). Anyone that can help ?
Thanks in advance.
Your connection data is using special characters and if you try to do this with GET method of NSURLConnection. It will Shows connection error. For this You have to use POST method like :
NSData *body = nil;
NSString *contentType = #"text/html; charset=utf-8";
NSURL *finalURL = #"YOUR URL WITH the ?input=";
NSString *yourString = #"geoX#35#geoY#65";
contentType = #"application/x-www-form-urlencoded; charset=utf-8";
body = [[NSString stringWithFormat:#"%#", yourString] dataUsingEncoding:NSUTF8StringEncoding];
if (nil==finalURL) {
finalURL = url;
}
NSMutableDictionary* headers = [[[NSMutableDictionary alloc] init] autorelease];
[headers setValue:contentType forKey:#"Content-Type"];
[headers setValue:mimeType forKey:#"Accept"];
[headers setValue:#"no-cache" forKey:#"Cache-Control"];
[headers setValue:#"no-cache" forKey:#"Pragma"];
[headers setValue:#"close" forKey:#"Connection"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:finalURL
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request setHTTPMethod:#"POST"];
[request setAllHTTPHeaderFields:headers];
[request setHTTPBody:body];
self.conn = [NSURLConnection connectionWithRequest:request delegate:self];

Objective C write to Remote URL

Ok, so I have the correct username / pass for a remote host, and I have a NSURL Object referring to the file on the server.
How can I possibly write data to that server via Objective-C? I cannot find anyone with this problem, so you help would be greatly appreciated!
I do it all the time with the program I am writing. The answer depends on what server you have installed and what languages it supports. If, as I think, you have PHP, just send a GET request to your server and instruct the PHP to write the data it receives.
This is a function of mine:
function checkInfo() {
$username = $_GET['username'];
$password = $_GET['password'];
connectToDataBase();
return returnSuccessObjectOn(isLoginInfoValid($username, $password));
}
On the client side:
NSURL *url = [NSURL URLWithString:kRequestLink];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:TIMEOUT];
OARequestParameter *reqCodeParameter = [[OARequestParameter alloc] initWithName:kParamReqCode value:[NSString stringWithFormat:#"%d",reqCode]];
[par addObject:reqCodeParameter];
[data enumerateKeysAndObjectsUsingBlock:composeRequestBlock];
[req setParameters:par];
NSLog(#"Sendind GET request: %#", [req description]);
activeConnection = [[NSURLConnection alloc] initWithRequest:req delegate:self startImmediately:YES];
As you can see I use blocks