Synchronous request or asynchronous when checking user's login data - iphone

In my application i need to implement verification if user has entered correct login and password or not. the login and the password are stored at the web server so i have to organize correct connection to the server. I'm an absolute beginner in everything about http requests and all that stuff. Actually i downloaded ASIHTTPRequest library and added it to my project just yesterday. My main problem is that i don't have an actual server by now (and i' m using just a conventional URL which later will be replaced with true server name but i want my code to be correct already)so i cannot test myself whether i'm doing things correctly or not.So my questions are:
1)What is the best way to organize verifying user's login and password? Should i use synchronous request or asynchronous? For all i know synchronous requests are rare in use cause they stop the application while the request is being performed but there's really nothing else needed to be done in this event so i'm a bit confused.What would you use?
2)I suppose verifying user's login and password by using http requests is pretty common task so there must be a general rule what kind of data the web server returns. I don't want to invent a wheel. should i use NSString returned by responseString to check if user's login and password match? What does server returns usually in such cases? How should my code look like? Something like
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:someUrl];
[request startSynchronous];
NSString *response = [request responseString];
if ([response isEqualToString:#"login and password match"])
//user enters next screen
else
//user is notified about the error
or something else? What would you do?
3)This request is not only i need to implement. Later i'm going to connect to the same URL with a different request. So how does the server know what kind of request is currently being used?
I really need your advice. Great thanks in advance

I have tried to answer your question,
Q:1. Synchronous or Asynchronous request model for login?
-> As per apple's documentation
A synchronous load is built on top of the asynchronous loading code made
available by the class. The calling thread is blocked while the asynchronous
loading system performs the URL load on a thread spawned specifically for
this load request.
also,
NSURLConnection provides support for downloading the contents of an
NSURLRequest in a synchronous manner using the class method
sendSynchronousRequest:returningResponse:error:. Using this method is
not recommended, because it has severe limitations:
The client application blocks until the data has been completely
received, an error is encountered, or the request times out.
Minimal support is provided for requests that require authentication.
There is no means of modifying the default behavior of response
caching or accepting server redirects.
As you are unaware of server side implementation, which may involve:
1. Redirection and other mechanisms for fulfilling the request.
2. It may require some proxy authentication or other similar stuff.
Q:2. What does server returns usually in such cases?
In general, a web service is implemented at server-side which returns XML or JSON as repsonse which you have to parse and use.
example response may look like:
for XML:
<auth>
<statusCode>0</statusCode>
<statusMessage>Login Successful.</statusMessage>
</auth>
for JSON
{
"statusCode" = "0"
"statusMessage" = "Login Successful."
}
tags(for XML) and keys(for JSON) will depend upon you sever implementation.
3. How does the server know what kind of request is currently being used?
-> The URL which you will use for request will tell server, what you are looking for?
for example
http://www.example.com/mywebapp/getItem?id="1";
Thanks,
or
http://www.example.com/mywebapp/removeItem?id="1";
The bold path item represents services which you are calling.

Related

Yii2 Reading PUT request body after oauth2 server already did it

I am working on REST API with oauth2 authorization.
For Oauth2 server i use https://github.com/bshaffer/oauth2-server-php
Php doc says here http://php.net/manual/en/wrappers.php.php
Prior to PHP 5.6, a stream opened with php://input could only be read once; the stream did not support seek operations. However, depending on the SAPI implementation, it may be possible to open another php://input stream and restart reading. This is only possible if the request body data has been saved. Typically, this is the case for POST requests, but not other request methods, such as PUT or PROPFIND.
In short it means that it is possible to read POST body twice, but not PUT.
But Oauth2 server reads it first time here https://github.com/bshaffer/oauth2-server-php/blob/develop/src/OAuth2/Request.php#L114
So when i read raw body in Yii2 Request, it is empty. (only on PUT, on POST and PATCH it is ok and can be read twice).
https://github.com/yiisoft/yii2/blob/master/framework/web/Request.php#L345
I know that this is kind of expected, no bugs. But what would be the solution for this?
Before you create that auth server, run this (depending in where you do authentication, you can use beforeAction(), or even init():
$content = Yii::$app->request->rawBody;
$authentication = Request::createFromGlobals();
if ($content)
$authentication->content = $content;
Now, I don't know how/where you use the component, so it might not fully work, but in theory it should.

Sending data to a website and getting results of search iOS

I am very new to iOS and I've just begun reading about HTTP requests and POST and GET methods. Let's say, for example, I want to have the user input a string, and then send that data to a website, (for this example, say www.rhymezone.com), search with that string, and get the results of that search within my application. Is this done with an HTTP post method? Or what? Any help / examples would be greatly appreciated. Also, if there are tutorials for this stuff, that would be appreciated as well.
For sake of example, here is what I've tried:
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://www.rhymezone.com/r/rhyme.cgi?Word=test&typeofrhyme=perfect&org1=syl&org2=l&org3=y"]];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSString *dataAsString=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"data: %#",dataAsString);
}
This outputs the entire source of the website (searching for rhymes of the word test). While I can certainly write a method to go through the source of the website and extract the words it returns, I feel like this is not correct. My way of getting rhymes of different words is simply to change the URL here, so where it says 'test' I change it to whatever the user inputs.
Thanks
Look into AFNetworking and RestKit.
It's easiest if you're calling a public API that uses JSON/XML, and then use a built in parser or a parser library to extract the data you want.
Simply downloading the contents of a URL is an HTTP GET request, such as going to a website.
This link talks a bit more about the difference between GET and POST.
When do you use POST and when do you use GET?
If I understand correctly what you are trying to do, I fear that the only option for you is sending the HTTP request (GET or POST according to what the website expects, just like you are doing) and then parse the result to filter all the information that is not relevant.
An alternative approach would be possible if you were using a website offering a REST API, or a JSON API so that you send the query and you get back just the information you need (in a specific format).
So, it depends strongly on the website you are using, but for the generic case, the only option you have is parsing.
(Or, you could display the full content of the page through UIWebView. This would not require explicitly setting up a connection, but I am not sure it is what you are trying to do.)
You are looking for a way to communicate with your website from your iOS application. The common approach is to get the string entered by the user, encode and send it as http request to a sort of script (webservice). This script will do all the stuff you want (search with this string). Then re-send the result to the client (your iOS app) as a http response which will be parsed in your iOS app(with a JSON parser for instance).
There is good resources around that, as an example, you may read this: http://www.raywenderlich.com/2965/how-to-write-an-ios-app-that-uses-a-web-service

ASIHTTPRequest, request sent twice

I´ve just started using ASIHTTPRequest for iOs and I have a small issue with it. All requests are sent twice to the server even though I only get one reply from the library to my delegate methods.
Both sync and async requests have this issue. I use Xcode 4 with ARC but have disabled it for ASIHTTPRequest by adding -fno-objc-arc as compiler flags.
Any idea what´s wrong..?
Code:
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request startSynchronous];
NSError *error = [request error];
if (!error) {
}
This has bitten me too. I was using a GET request to validate a multi-use voucher code on a server. When we added a rate limitation for redeeming codes some customers reported hitting the limit before they should have. Turns out that some of the validations triggered two redeems.
Your request is using the GET method.
The default behavior when using GET is to allow persistent connections (the Keep-Alive HTTP header).
When using a persistent connection your GET request might get retransmitted if something on the network looks wonky (that's a technical term) instead of the request just failing. This is usually desirable because GET requests often do not have any side effects on the server.
POST or PUT requests on the other hand default to not use a persistent connection and will not retransmit your operation, which could well be a credit card purchase or something else with significant side effects.
If you wish to prevent your ASIHTTPRequest GET sometimes sending 2 or more server requests (due to network issues outside your control) you can simply set this flag:
request.shouldAttemptPersistentConnection = NO;
This should take care of the spurious GET duplicates on the server.
Thank you for your replies. I moved to the new MKNetworkKit and never looked back at ASIHttpRequest. https://github.com/MugunthKumar/MKNetworkKit
Øystein
It might be sending a HEAD request to fetch the response size followed by a GET request to actually get the content. See this section of the documentation for more information.
It could be because persistent connections are in use, so you're seeing a failed request on a old connection followed by a working request on a new connection. (GregInYEG is also correct that it could be a HEAD request.)
If you gather a network trace using a tool like wireshark or charlesproxy then it would be possible to see exactly what is happening.

How to implement NTLM Authentication for UIWebView?

I have a use case where a UIWebView may need to connect with a web server secured with NTLM. I also have a use case where I already have the credentials to be passed. So instead of forcing the user to enter them, how do I perform the handshake with the UIWebView?
UPDATE:
Using this method here works well enough when you are doing simple GET requests, but utterly fails when doing POSTs, for the mere fact that it is doing a GET after it is posted.
The ASIHttpRequest and ASIWebPageRequest have the same problem. GET requests work wonders, but any POSTs just don't work. If only the world worked on just GET requests.
I have been able to use this method of including the username and password in the HTTP request string, but that is so grossly insecure as to defy reason for using it. Using a sniffer I am able to see the three-way handshake occur without any problems on both GET and POST requests.
You can set the default credential:
NSURLProtectionSpace *protectionSpace = [[NSURLProtectionSpace alloc]
initWithHost: _host
port: 80
protocol: #"http"
realm: _host
authenticationMethod:NSURLAuthenticationMethodNTLM];
[[NSURLCredentialStorage sharedCredentialStorage] setDefaultCredential:[NSURLCredential credentialWithUser:_username password:_password persistence:NSURLCredentialPersistenceForSession] forProtectionSpace:protectionSpace];
Now you can let your webviews do the request, and when it encounters your protenctionSpace it logs in using the given credentials
As of iOS 3.2 and 4.1, there is no public delegate for intercepting the NTLM challenge. There is, however, a private API that can be overriden to give proper support for this. Since this would put your application in danger of being rejected, I will forgo posting the code because it is of no worth for App Store development at the present time.
If you're willing to try some experimental code, you could use ASIWebPageRequest.
It would be a bit hacky, as you'd have to download the page content with ASIWebPageRequest, load it into a UIWebView, then capture any link clicks in the web view and repeat the process again (if the content at the URL requires authentication). Also, I think you'd have to manage your own history stack.
I don't think it would be easy, but it does seem doable, and it seems like it should work as long as the ASIWebPageRequest code isn't too buggy or limited.
UIWebView doesn't support authentication at all. Up to iPhone OS 3.1, you could add credentials to the central credential storage and UIWebView would at least work with basic authentication. But starting with iOS 4.0, I don't see any way to use authentication (except cookie or URL based forms authentication).

Is it possible to send database query within a NSUrl request?

i am developing iphone application which connects to a php page using NSUrl request.The php page on the server side ,in turn,connects to the database (mysql) to perform transactions.Till now i was passing only parameters to the actual query on php page which was working fine.But when sending query from iphone end through NSUrl ,either connection fails or the query is assigned a nil value.Is there any way to send query using NSUrl or some othr method?
It sounds like you have a working server-side script that returns data in response to well-formed requests, so it's a matter of getting your NSURLConnection to make requests in the appropriate fashion. If you have a known-good request, you can inspect on the properties of the NSURLRequest object you're creating (HTTPBody, URL, etc.) and see where you're going wrong. Also pay attention to any error messages you might be receiving in your delegate methods (i.e., connection:didFailWithError:)