Login credential issue using NSURL Methods - iphone

I have an webservices url which appends with password. When I run the application by giving correct password, the application is running and at the same time when I run the app with wrong credentials. the app is running, I didn't have an idea to get rid out of the issue. My code is here:
NSString *post =[[NSString alloc] initWithFormat:#"password=%#",[password text]];
NSLog(#"PostData: %#",post);
NSURL *url=[NSURL URLWithString:[NSString stringWithFormat:#"http://myexample.com/Accountservice/Secure/ValidateAccess?password=abcd&type=1"]];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLRequest *request1 = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:post] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request1 delegate:self startImmediately:YES];
if(!connection){
NSLog(#"connection failed");
}
else{
NSLog(#"connection succeeded");
}
If I gave 'abcd' as password connection is successfully is displaying. If I gave wrong password connection successfully is displaying. How can I solve the issue? If I gave wrong password need to display an alert.

This control structure here is the problem:
if(!connection){
NSLog(#"connection failed");
}
else {
NSLog(#"connection succeeded");
}
This doesn't check for a bad connection, this checks whether or not the connection object is equal to 0 (nil). Obviously, having initialized it on the line above, the else statement will always log, giving you the false impression that your connection had succeeded. You should become the connection's delegate, and respond to the appropriate delegate methods instead.

The issue may be with the url you are using
Fire the url in the browser and see what it returnes
try add the url params with single quotes accesscode='abcd'
It is not a good practice to pass the credentials via this way.
You could use POST method with some valid encryption to prevent the security issues that can occur
SOLUTION
Try this
NSString *urlString=#"http://myexample.com/Accountservice/Secure/ValidateAccess?";
self.responseData = [NSMutableData data];
NSString *post =[NSString stringWithFormat:#"username=%#&password=%#",userNameTextField.text,passwordTextField.text];
NSData *postData=[post dataUsingEncoding:NSUTF8StringEncoding];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLConnection *connection0= [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection0 start];

Related

JSON parsing, How to get response from server

I have the following details, for get the data from server. What is the use of methodIdentifier and web service name ?
{"zip":"12345","methodIdentifier":"s_dealer"}
url:- http://xxxxxxxxxxxxxxx.com/api.php
method: post
web service name: s_dealer
response : {"success":"0","dealer":[info...]}
I don't know how to send zip number "12345" with the url. Please direct me on right direction. I use the following.
-(void)IconClicked:(NSString *)zipNumber
{
NSString *post = [NSString stringWithFormat:#"&zipNumber=%#",zipNumber];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d",[postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://xxxxxxxxxxxxxxxxxxx.com/api.php"]]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if(conn)
{
NSLog(#"Connection Successful");
}
else
{
NSLog(#"Connection could not be made");
}
receivedData = [[NSMutableData alloc]init];
}
when i print the response in console :\"Unexpected end of string\"
Without knowing more about the API, I can't be certain about your requirements, but it seems that the server is expecting the request to contain JSON. The way you currently are creating the body for the request is using standard POST variables.
Have you tried changing:
NSString *post = [NSString stringWithFormat:#"&zipNumber=%#",zipNumber];
to:
NSString *post = [NSString stringWithFormat:#"{\"zip\":\"%#\",\"methodIdentifier\":\"s_dealer\"}",zipNumber];
Regarding your other questions, I'm guessing that there is a single URL for the API. The methodidentifier is used by the server in order to determine which server method(s) to run.
You get this error because you do not get a json as a response, but an error from Apache (or whatever), that has different structure, and json cannot parse it. Try my method to initiate the connection, in order to gain a successful one.
Declare a NSURLConnection property and synthesize it. Now:
NSString *post = [NSString stringWithFormat:#"zipNumber=%#",zipNumber];
NSString *toServer = [NSString stringWithString:#"your server with the last slash character"];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#api.php?", toServer]];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *urlRequest = [[[NSMutableURLRequest alloc] init] autorelease];
[urlRequest setURL:url];
[urlRequest setHTTPMethod:#"POST"];
[urlRequest setValue:postLength forHTTPHeaderField:#"Content-Length"];
[urlRequest setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[urlRequest setValue:#"utf-8" forHTTPHeaderField:#"charset"];
[urlRequest setHTTPBody:postData];
[urlRequest setTimeoutInterval:30];
NSURLConnection *tmpConn = [[[NSURLConnection alloc] initWithRequest:urlRequest delegate:self] autorelease];
self.yourConnectionProperty = tmpConn;
Now you work with self.yourConnectionProperty in connection delegates. Cheers!
hey bro check my answer for same problem may help you... You have to use the NSURLConnection Delegates to get the data
Could not make Json Request body from Iphone

Not receiving data from NSMutableURLRequest (iPhone app sync)

In the past, I created an iPhone app which relies on a sqlite database updated by a php page. When you access the PHP page, it prints out a dump of a sqlite database and the app runs the various queries to update the sqlite database. My previous app worked fine in this manner and would update accordingly. I recently tried to apply the same process to a new app with a much bigger database. I have run into problems.
What I am doing is sending some post variables to a PHP page which recognizes the POST and echoes out the sqlite commands to update the database. The problem is that it takes a few seconds for the page to print the commands. If I have the page print some static text, I get it in my NSLog(#"Response data is going to be ==> %#", result); command. If I have to extract the information from my MySQL database, it takes about 3-5 seconds and then prints (on my normal browser). When I run the app, however, it says that Response data is going to be ==> (null) instead of the commands.
Can anyone shed some light on what might be happening? I know that this works when it doesn't print a lot of stuff and when it is static. The dynamic part makes it return null for some reason.
Help appreciated.
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlBase]];
[request setHTTPMethod:#"POST"];
[request setTimeoutInterval:60.0];
NSData *post = [myParameters dataUsingEncoding: NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d",[post length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Current-Type"];
[request setHTTPBody:post];
[request setHTTPBody:[myParameters dataUsingEncoding:NSUTF8StringEncoding]];
// set headers
NSString *contentType = [NSString stringWithFormat:#"text/plain"];
NSHTTPURLResponse *urlResponse = nil;
NSError *error = [[NSError alloc] init];
NSData *responseData = [NSURLConnection sendSynchronousRequest:request
returningResponse:&urlResponse
error:&error];
NSString *result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"Response data is going to be ==> %#", result);
try to understand this code..it helps u.
NSString *soapMessage=[NSString stringWithFormat:#" YOUR WEB SERVICE CODE",myTxt1.text,myTxt2.text];
NSLog(#"%#",soapMessage);
//-----------create connection
NSURL *url=[NSURL URLWithString:#"http://your local host webservice url"];
NSMutableURLRequest *theRequest=[NSMutableURLRequest requestWithURL:url];
NSString *msgLength=[NSString stringWithFormat:#"%d",[soapMessage length]];
//----------sending request
[theRequest addValue: #"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[theRequest addValue: #"http://tempuri.org/AutenticateUser" forHTTPHeaderField:#"SOAPAction"];
[theRequest addValue: msgLength forHTTPHeaderField:#"Content-Length"];
[theRequest setHTTPMethod:#"POST"];
[theRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection *theConnection=[[NSURLConnection alloc]initWithRequest:theRequest delegate:self];
//[activityIndicator startAnimating];
if ( theConnection )
{
webData = [[NSMutableData data] retain];
}
else
{
NSLog(#"theConnection is NULL");
}

Cant Post To Server Well

i am trying to post to a server in the following code.
i cant receive the response that i need to get.
think i am making something wrong, need some help
NSString *uuid = #"acdede9b-6fa6-44d0-8837-cd11771139be";
NSString *rec = #"ewoJInNpZ25hdHVyZSIgPSAiQWphZElyM2hFclc2L0xReDYwNGtpZ3FpZmxZUll4MTdJUUN1VUQ3UG1LS2tCNU1yeUxvU2NOejdnKzVlYnZBS001TnV2R3dOVWRmcmFEeHN3eElONVJXZXFoc1Q0OEJMUVlXNzBnWmFyTUhVbW81SW1BdFVvZy9PWlQyTkVvdW5DNW5uR3JBQll0K0Q2VFdZK1hEL0NIczczcmpqcmtONnNFalNmR05kNEg4K0FBQURWekNDQTFNd2dnSTdvQU1DQVFJQ0NHVVVrVTNaV0FTMU1BMEdDU3FHU0liM0RRRUJCUVVBTUg4eEN6QUpCZ05WQkFZVEFsVlRNUk13RVFZRFZRUUtEQXBCY0hCc1pTQkpibU11TVNZd0pBWURWUVFMREIxQmNIQnNaU0JEWlhKMGFXWnBZMkYwYVc5dUlFRjFkR2h2Y21sMGVURXpNREVHQTFVRUF3d3FRWEJ3YkdVZ2FWUjFibVZ6SUZOMGIzSmxJRU5sY25ScFptbGpZWFJwYjI0Z1FYVjBhRzl5YVhSNU1CNFhEVEE1TURZeE5USXlNRFUxTmxvWERURTBNRFl4TkRJeU1EVTFObG93WkRFak1DRUdBMVVFQXd3YVVIVnlZMmhoYzJWU1pXTmxhWEIwUTJWeWRHbG1hV05oZEdVeEd6QVpCZ05WQkFzTUVrRndjR3hsSUdsVWRXNWxjeUJUZEc5eVpURVRNQkVHQTFVRUNnd0tRWEJ3YkdVZ1NXNWpMakVMTUFrR0ExVUVCaE1DVlZNd2daOHdEUVlKS29aSWh2Y05BUUVC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ERXhMVEV4TFRJNElEQXdPakUwT2pBd0lFVjBZeTlIVFZRaU93b0pJbWwwWlcwdGFXUWlJRDBnSWpRM05USXhNVFUzTlNJN0Nna2laWGh3YVhKbGN5MWtZWFJsTFdadmNtMWhkSFJsWkNJZ1BTQWlNakF4TVMweE1TMHlPQ0F3TVRveE5Eb3dNQ0JGZEdNdlIwMVVJanNLQ1NKbGVIQnBjbVZ6TFdSaGRHVWlJRDBnSWpFek1qSTBOREk0TkRBd01EQWlPd29KSW5CeWIyUjFZM1F0YVdRaUlEMGdJbU52YlM1aGJXOTBaV05vTGs5dVpWbGxZWElpT3dvSkluUnlZVzV6WVdOMGFXOXVMV2xrSWlBOUlDSXhNREF3TURBd01ERTBPRE00TURnMUlqc0tDU0p2Y21sbmFXNWhiQzF3ZFhKamFHRnpaUzFrWVhSbElpQTlJQ0l5TURFeExURXhMVEkzSURJeU9qRXpPak16SUVWMFl5OUhUVlFpT3dvSkltOXlhV2RwYm1Gc0xYUnlZVzV6WVdOMGFXOXVMV2xrSWlBOUlDSXhNREF3TURBd01ERTBPREk1TVRJeElqc0tDU0ppYVdRaUlEMGdJbU52YlM1aGJXOTBaV05vTG1Gd2NHTnBaR1Z1ZEVGd2NDSTdDZ2tpWW5aeWN5SWdQU0FpTVM0d0lqc0tmUT09IjsKCSJlbnZpcm9ubWVudCIgPSAiU2FuZGJveCI7CgkicG9kIiA9ICIxMDAiOwoJInNpZ25pbmctc3RhdHVzIiA9ICIwIjsKfQ==";
NSString *ServerContent = [NSString stringWithFormat:#"registerRecipt.aspx?udid=%#&receipt=%#",uuid,rec];
NSData *requestdata = [ServerContent dataUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"myserverurl"]];
request.timeoutInterval = 20;
[request setHTTPMethod:#"POST"];
[request setHTTPBody:requestdata];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
error
The page cannot be displayed Open IIS Help, which is accessible in IIS Manager (inetmgr),
Try setting the Content-Length header:
[request setValue:[NSString stringWithFormat:#"%d", [requestData length]]
forHTTPHeaderField:#"Content-Length"];

NSMutableURLRequest proper posting

So I am trying to log into my site using an NSMutableURLRequest which presents the credentials via a post. As a noobie, I have some questions about the functionality of this method to make sure I am understanding it.
NSString *post = [NSString stringWithFormat:#"username=%#&password=%#&TARGET=%#",LoginId,LoginPwd,target];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d",[postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setHTTPShouldHandleCookies:YES];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"https://somelogin.mycomp.verify.fcc"]]];
//[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Current-Type"];
[request setHTTPBody:postData];
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];
Now this will automatically handle any redirects via the delegate method correct? It will also collect any cookies along the way? Also, should I be using an asynchronous request instead? Thanks!
UPDATE:
So I have deduced that some of the cookies are being ignored by the request and subsequent redirects. Does anyone know why that may be happening?
you can do something like this when logging in synchronously... the code is not perfect, but this is the general idea.
look here for documentation
https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/URLLoadingSystem/Articles/AuthenticationChallenges.html#//apple_ref/doc/uid/TP40009507-SW1
// credentials set here
NSURLCredential *creds = [NSURLCredential credentialWithUser:LoginId password:LoginPwd
persistence:NSURLCredentialPersistenceForSession];
NSURLProtectionSpace *protectionedSpace = [[NSURLProtectionSpace alloc]
initWithHost:#"mycomp.verify.fcc"
port:8443
protocol:#"https"
realm:nil
authenticationMethod:nil];
[[NSURLCredentialStorage sharedCredentialStorage] setDefaultCredential:creds
forProtectionSpace:protectionedSpace];
// removed credentials from line...
NSString *post = [NSString stringWithFormat:#"TARGET=%#",target];
here is a tutorial that does it asynchronously
http://iosdevelopertips.com/networking/handling-url-authentication-challenges-accessing-password-protected-servers.html

Problem with NSMutableURLRequest

i have the following method
-(void)request
{
responseData = [[NSMutableData data] retain];
NSString *post = [NSString stringWithFormat:#"id=%d&a_id=&d",1,1];
NSLog(#"%#",post);
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:kWebURL#"/req/request.php"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
[postLength release];
[postData release];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[connection release];
}
My problem is that there is a leak with the nsmutableurlrequest object. I think i should release it somewhere, but when i try to do so, i get an exec_bad_access. Whereever i try to release it i get that error at the end of the connectionDidFinishLoading method.
EDIT: It looks like i can either release the NSURLConnection object OR the NSMutableURLConnection object.
If i try to remove both of them when i should, i get an exec_bad_access
I believe your problem is with your releasing of postLength and postData. You didn't allocate either of these, but created them with convenience methods. You should take those two lines out, and then you should be okay to release your NSMutableURLRequest.