Google App Engine with ClientLogin Interface for Objective-C
Asked Answered
A

7

10

I'm experiencing the same problem in this previous stackoverflow.com post.

Specifically, I seem to be able to get the "Auth" token correctly, but attempts to use it in the header when I access later pages still just return me the login page's HTML.

Following links related to this post, I've determined that you need to make a subsequent call to this URL.

A call to the URL will then give you an ACSID cookie which then needs to be passed in subsequent calls in order to maintain an authenticated state.

When requesting this cookie, I've read various posts saying you need to specify your original auth token by appending it to the query string such that:

?auth=this_is_my_token

I've also read that you should set it in the http header as described in google's documentation such that a http header name/value is:

Authorization: GoogleLogin auth=yourAuthToken

I've tried both approaches and am not seeing any cookies returned. I've used Wireshark, LiveHttpHeaders for Firefox, and simple NSLog statements trying to see if anything like this is returned.

Below is the code snippet I've been using.

NSURL* url = [NSURL URLWithString:[NSString stringWithFormat:@"http://yourapp.appspot.com/_ah/login?auth=%@", [token objectForKey:@"Auth"]]];
NSHTTPURLResponse* response;
NSError* error;
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
[request setValue:[NSString stringWithFormat:@"GoogleLogin auth=%@", [token objectForKey:@"Auth"]] forHTTPHeaderField:@"Authorization"];
NSData * data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];  

//show me all header fields
NSLog([[response allHeaderFields] description]);

//show me the response
NSLog(@"%@", [[[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding] autorelease]);
NSArray * all = [NSHTTPCookie cookiesWithResponseHeaderFields:[response allHeaderFields] forURL:[NSURL URLWithString:@"http://yourapp.appspot.com/_ah/login"]];

//show me all cookies
for (NSHTTPCookie *cookie in all) 
{
    NSLog(@"Name: %@ : Value: %@", cookie.name, cookie.value); 
}

I hope you can use ClientLogin for Google App Engine code.

Applecart answered 23/1, 2009 at 4:37 Comment(0)
A
16

Adding sample code to this question because someone contacted me directly about my solution. Note that you must set the "service" parameter equal to "ah" on the initial token request.

Initial Request of Token [done synchronously] NOTE: the "service" parameter is set to "ah" and the "source" is just set to "myapp", you should use your app name.

//create request
NSString* content = [NSString stringWithFormat:@"accountType=HOSTED_OR_GOOGLE&Email=%@&Passwd=%@&service=ah&source=myapp", [loginView username].text, [loginView password].text];
NSURL* authUrl = [NSURL URLWithString:@"https://www.google.com/accounts/ClientLogin"];
NSMutableURLRequest* authRequest = [[NSMutableURLRequest alloc] initWithURL:authUrl];
[authRequest setHTTPMethod:@"POST"];
[authRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-type"];
[authRequest setHTTPBody:[content dataUsingEncoding:NSASCIIStringEncoding]];

NSHTTPURLResponse* authResponse;
NSError* authError;
NSData * authData = [NSURLConnection sendSynchronousRequest:authRequest returningResponse:&authResponse error:&authError];  

NSString *authResponseBody = [[NSString alloc] initWithData:authData encoding:NSASCIIStringEncoding];

//loop through response body which is key=value pairs, seperated by \n. The code below is not optimal and certainly error prone. 
NSArray *lines = [authResponseBody componentsSeparatedByString:@"\n"];
NSMutableDictionary* token = [NSMutableDictionary dictionary];
for (NSString* s in lines) {
    NSArray* kvpair = [s componentsSeparatedByString:@"="];
    if ([kvpair count]>1)
        [token setObject:[kvpair objectAtIndex:1] forKey:[kvpair objectAtIndex:0]];
}

//if google returned an error in the body [google returns Error=Bad Authentication in the body. which is weird, not sure if they use status codes]
if ([token objectForKey:@"Error"]) {
    //handle error
};

The next step is to get your app running on google app engine to give you the ASCID cookie. I'm not sure why there is this extra step, it seems to be an issue on google's end and probably why GAE is not currently in their listed obj-c google data api library. My tests show I have to request the cookie in order sync with GAE. Also, notice I don't do anything with the cookie. It seems just by requesting it and getting cookied, future requests will automatically contain the cookie. I'm not sure if this is an iphone thing bc my app is an iphone app but I don't fully understand what is happening with this cookie. NOTE: the use of "myapp.appspot.com".

NSURL* cookieUrl = [NSURL URLWithString:[NSString stringWithFormat:@"http://myapp.appspot.com/_ah/login?continue=http://myapp.appspot.com/&auth=%@", [token objectForKey:@"Auth"]]];
    NSLog([cookieUrl description]);
    NSHTTPURLResponse* cookieResponse;
    NSError* cookieError;
    NSMutableURLRequest *cookieRequest = [[NSMutableURLRequest alloc] initWithURL:cookieUrl];

    [cookieRequest setHTTPMethod:@"GET"];

    NSData* cookieData = [NSURLConnection sendSynchronousRequest:cookieRequest returningResponse:&cookieResponse error:&cookieError];   

Finally, I can post json to my gae app. NOTE: the snippet below is an async request. We can handle responses by implementing didReceiveResponse, didReceiveData, didFailWIthError.

NSURL* url = [NSURL URLWithString:[NSString stringWithFormat:@"http://myapp.appspot.com/addRun?auth=%@", mytoken]];
    NSMutableURLRequest* request = [[NSMutableURLRequest alloc] initWithURL:url];
    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:@"my http body";

    NSURLConnection *connectionResponse = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    if (!connectionResponse) {
        NSLog(@"Failed to submit request");
    } else {
        NSLog(@"Request submitted");
    }
Applecart answered 26/1, 2009 at 1:8 Comment(2)
It's a Cocoa thing... "The URL loading system automatically sends any stored cookies appropriate for an NSURLRequest unless the request specifies not to send cookies. Likewise, cookies returned in an NSURLResponse are accepted in accordance with the current cookie acceptance policy."Cindicindie
I don't see how anyone could figure this out from Google's documentation. Thanks very much for the experimentation.Outsmart
W
1

1st - thanks for the great post it really got me started.

2nd - I have been slugging it out with my app, trying to POST to the GAE while authenticated.

This is the request is built when POSTing, once you have acquired the authtoken:

    NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];


[request setURL:[NSURL URLWithString:url]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"image/png" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];

[request setValue:authtoken forHTTPHeaderField:@"auth"];  // <-- the magic
  • mattb
Waneta answered 23/1, 2009 at 4:37 Comment(0)
C
1

Check out the code that does this in the official SDK. The latest SDK release even has it split into its own file.

Cagey answered 23/1, 2009 at 19:22 Comment(1)
Same issue. Here's what I don't understand, if i just plug: myapp.appspot.com/_ah/login?continue=http://myapp.appspot.com/… into a browser, shouldn't i see the cookie get set???Applecart
H
1

I created a few obj-c classes for implementing ClientLogin, including support for Google App Engine:

http://github.com/cameronr/GoogleAppEngineAuth

Hebrews answered 8/3, 2010 at 22:58 Comment(0)
N
0

Note that Google has recently changed the way authorization failure is indicated. They used to place an Error token in the response. Now they just return a 403 (Forbidden) status. This broke my code!

Nucleonics answered 3/12, 2009 at 15:11 Comment(0)
T
0

Thank for this post and especially the answer from Keith but it does not works for me. Even if it seems ok for me ... very strange.

I check this post (How do you access an authenticated Google App Engine service from a (non-web) python client?) which talk about doing the same thing in python. I test it and it works.

And the objective C code proposed by Keith is really similar to the python code.

But when I try to get the "Auth" token authData contains Error=BadAuthentication.

Some one got an idea about possibles problems ?

Tsan answered 19/2, 2010 at 22:13 Comment(1)
ok my problems is just that parameter of the request (email, passwd, ....) have to be "encoded". Like what is done in python with "urllib.urlencode". Not found yet how to done that in objc but should be ok. sorryTsan
S
0

Using HOSTED_OR_GOOGLE is wrong, and I will explain why.

There are two kinds of accounts in the Google world. The ones you create for GMail, etc are "Google" accounts. The ones you create for Apps for Domains are "Hosted" accounts. You can use a Hosted Account email to make a Google Account, thus creating an email address that is associated with both kinds of accounts.

Your Google App Engine app can be configured to work with (1) Google Accounts or (2) Hosted Accounts for a particular domain.

Assume that we are developing an app for Google Accounts. A user enters in an email address that is associated with a Google Account and a Hosted Account. Google will use their Google Account for the login. This all works fine.

Now, if we use ClientLogin with this same email address and use HOSTED_OR_GOOGLE for the account type, login will be successful, but it will use the Hosted Account, since the Hosted Account takes precedence. As I mentioned above, you cannot use a Hosted Account for an app that expects a Google Account. So the authentication will not work.

So, when using ClientLogin to authenticate with a Google App Engine app, you need to use GOOGLE for the account type if the app is for Google Accounts, or HOSTED for the account type if the app is for a domain.

Snarl answered 6/3, 2010 at 12:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.