使用NSURL方法登录凭据问题

时间:2013-03-12 05:07:54

标签: iphone ios objective-c nsurlconnection

我有一个附加密码的webservices网址。当我通过提供正确的密码来运行应用程序时,应用程序正在运行,同时我使用错误的凭据运行应用程序。该应用程序正在运行,我没有想法摆脱这个问题。我的代码在这里:

     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");
        }

如果我给了abcd'密码连接成功显示。如果我提供错误的密码连接成功显示。我该如何解决这个问题?如果我给错了密码需要显示警告。

2 个答案:

答案 0 :(得分:1)

这里的控制结构是问题所在:

if(!connection){
    NSLog(@"connection failed");
}
else {
    NSLog(@"connection succeeded");
}

这不会检查连接是否错误,这会检查连接对象是否等于0(nil)。显然,在上面的行中初始化后,else语句将始终记录,给您错误的印象,即您的连接已成功。您应该成为连接的delegate,并响应相应的委托方法。

答案 1 :(得分:0)

问题可能在于您正在使用的网址

  1. 在浏览器中触发网址并查看其返回的内容
  2. 尝试使用单引号accesscode ='abcd'
  3. 添加url params

    通过这种方式传递凭据不是一个好习惯。 您可以使用POST方法和一些有效的加密来防止可能发生的安全问题

    <强>解 试试这个

      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];
    
相关问题