使用与Django和ASIHttpRequest的用户身份验证/会话

时间:2012-04-23 18:56:55

标签: ios django authentication asihttprequest session-cookies

我正在尝试在iOS中创建一个基本身份验证系统,向Django发送POST,并在Django端验证用户并启动会话。现在,我可以通过将值作为URL中的数据传递并对其进行身份验证来发送用户信息,但是如何从Django响应中检索会话数据或cookie?当我尝试存储或打印出cookie时,它告诉我数组是空的。我已经尝试过request.requestCookies和request.responseCookies。

NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:@"test_user", @"username", @"pass", @"password", nil];

NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://127.0.0.1:8000/login/"]];

NSError *error;
NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:0 error:&error];

if ( error ) {
    NSLog( @"ERROR - %@", error.localizedDescription );
} else {
    __block ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    [request addRequestHeader: @"Content-Type" value:@"application/json; charset=utf-8"]; 
    [request appendPostData:data];
    [request setRequestMethod:@"POST"];

    [request setCompletionBlock:^{

        UIAlertView *alerView = [[UIAlertView alloc] initWithTitle:@"Login"
                                                           message:@"Login was sent"
                                                          delegate:nil
                                                 cancelButtonTitle:nil
                                                 otherButtonTitles:@"Ok", nil];
        [alerView performSelectorOnMainThread:@selector(show) withObject:nil waitUntilDone:NO];

        NSLog(@"RESPONSE: %@", [[NSString alloc] initWithData:request.responseData encoding:NSUTF8StringEncoding]);//, [request.requestCookies objectAtIndex:0]);
        NSLog(@"COOKIE: %@", [request.requestCookies objectAtIndex:0]);
        [ASIHTTPRequest addSessionCookie:[request.requestCookies objectAtIndex:0]];

    }];

1 个答案:

答案 0 :(得分:0)

好的,所以我解决了这个问题,事实证明在服务器端我输入了数据但没有正式登录Django(没有返回正确的cookie)这意味着我的应用程序没有收到正确的标题