1

I'm new in iOS programming. I made iOS app with connection to MSSQL.

It works fine when online dialog authorization to server deactivated

Accordingly when we activate authorization my app does not work. Server authorization picture.

How can I specify authorization data in my app? How can I fill login and pass background in app? And whether it be safe?

My code is the next:

ViewController.m

#import "ViewController.h"
#import "SBJson.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void) alertStatus:(NSString *)msg :(NSString *)title
{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title
                                                        message:msg
                                                        delegate:self
                                               cancelButtonTitle:@"Ok"
                                               otherButtonTitles:nil, nil];  
     [alertView show];
}

- (IBAction)loginClicked:(id)sender {
    NSInteger success = 0;
    @try {

    if([[self.txtUsername text] isEqualToString:@""] || [[self.txtPassword text] isEqualToString:@""] ) {
        [self alertStatus:@"Please, enter login and password!" :@"Error" :0];
    } else {

    // login in app (this login is use for entrance to mssql base)

        NSString *post =[[NSString alloc] initWithFormat:@"username=%@&password=%@",[self.txtUsername text],[self.txtPassword text]];
        NSLog(@"PostData: %@",post);

        NSURL *url=[NSURL URLWithString:@"https://*****/file.php"];
        NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
        NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[postData length]];

        NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
        NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: self delegateQueue: nil];

        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
        [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];

        NSURLSessionDataTask *urlData = [defaultSession dataTaskWithRequest:request
                                                        completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                                                            NSLog(@"Response:%@ %@\n", response, error);
                                                            if(error == nil)
                                                            {
                                                                NSString *text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
                                                                NSLog(@"Response ==> %@", text);

                                                                    NSDictionary *jsonData = [NSJSONSerialization
                                                                                              JSONObjectWithData:data
                                                                                              options:NSJSONReadingMutableContainers
                                                                                              error:&error];

                                                                    NSInteger *success = [jsonData[@"success"] integerValue];
                                                                    NSLog(@"Success: %ld",(long)success);

                                                                    if(success == 1)
                                                                    {
                                                                        NSLog(@"Login SUCCESS");
                                                                        dispatch_async(dispatch_get_main_queue(), ^ {
                                                                            [self performSegueWithIdentifier:@"goto_login" sender:self];
                                                                        });

                                                                    } else {

                                                                        [self alertStatus:@"Login/password is wrong!" :@"Error" :0];
                                                                    }

                                                            }
                                                            else
                                                            {
                                                                [self alertStatus:@"Connection error!" :@"Error!" :0];
                                                            }
                                                        }];

        [urlData resume];
    }
     }
     @catch (NSException * e) {
        NSLog(@"Exception: %@", e);
         [self alertStatus:@"Incorrect login/password!" :@"Error!" :0];
     }
 }

- (void) alertStatus:(NSString *)msg :(NSString *)title :(int) tag
{
     UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title
                                                    message:msg
                                                   delegate:self
                                          cancelButtonTitle:@"Ok"
                                          otherButtonTitles:nil, nil];
     alertView.tag = tag;
     dispatch_async(dispatch_get_main_queue(), ^ {
         [alertView show];
     });
 }

 - (IBAction)backgroundClick:(id)sender {
     [self.txtPassword resignFirstResponder];
     [self.txtUsername resignFirstResponder];
 }

 // for login to server 
- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler
{
     if(challenge.previousFailureCount == 0)
    {
        NSString *user = @"*****";
        NSString *password = @"*****";
        NSURLCredentialPersistence persistence = NSURLCredentialPersistenceForSession;


        NSURLCredential *credential = [NSURLCredential credentialWithUser:user password:password persistence:persistence];

       completionHandler(NSURLSessionAuthChallengeUseCredential,credential);
    }
    else
    {
        NSLog(@"%s: challenge.error = %@",__FUNCTION__, challenge.error);
       completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
    }
 }

 @end

And error is the next:

2016-01-25 17:10:50.398 Report[751:22264] Response:<NSHTTPURLResponse: 0x7fc691cf22c0> { URL: https://*****/file.php } { status code: 401, headers {
Connection = close;
"Content-Length" = 484;
"Content-Type" = "text/html; charset=iso-8859-1";
Date = "Mon, 25 Jan 2016 14:10:50 GMT";
Server = "Apache/2.2.3 (CentOS)";
"Www-Authenticate" = "Basic realm=\"Please enter login and pass for SOC\"";
 } } (null)
 2016-01-25 17:10:50.402 Report[751:22264] Response ==> <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
 401 Authorization Required

My php is next

file.php

<?php

// array for JSON response
$response = array();

// include db connect class
require_once '/db_connect.php';

// connecting to db
$db = new DB_CONNECT();

mssql_query("SET NAMES 'utf8'");
mssql_query("SET CHARACTER SET 'utf8'");

// Request type is check Login
 $password=$_POST["password"];
 $username=$_POST["username"];

// check for user

if (!empty($_POST)) {
  if (empty($_POST['username']) || empty($_POST['password'])) {
  // Create some data that will be the JSON response 
          $response["success"] = 0;
          $response["message"] = "Enter login/pass!";         
          die(json_encode($response));
   }
   $query = " SELECT * FROM users WHERE username = '$username'and  password='$password'";   
   $sql1=mssql_query($query);
   $row = mssql_fetch_array($sql1);
  if (!empty($row)) {
        $response["success"] = 1;
        $response["message"] = "Authorization is successfull!";
        die(json_encode($response));
   }
  else{   
       $response["success"] = 0;
       $response["message"] = "Incorrect login/pass!";
   die(json_encode($response));
  }
  }
  else{ 
  $response["success"] = 0;
           $response["message"] = "Enter login/pass!";
  die(json_encode($response));
  } 
  mssql_close();
  ?>
?>

db_config.php

<?php
 define('DB_USER', "****"); // db user
 define('DB_PASSWORD', "****"); // db password (mention your db password here)
 define('DB_DATABASE', "****"); // database name
 define('DB_SERVER', "****"); // db server
?>

db_connect.php

<?php
class DB_CONNECT {
    // constructor
    function __construct() {
        // connecting to database
        $this->connect();
    }
    // destructor
    function __destruct() {
        // closing db connection
        $this->close();
   }
    function connect() {
        // import database connection variables
        require_once __DIR__ . '/db_config.php';
        // Connecting to mssql database
        $con = mssql_connect(DB_SERVER, DB_USER, DB_PASSWORD) or die(mssql_error());
        // Selecing database
        $db = mssql_select_db(DB_DATABASE) or die(mssql_error()) or die(mssql_error());
        // returing connection cursor
         return $con;
    }
    function close() {
        // closing db connection
        mssql_close();
    }
}
?>
Maria
  • 11
  • 4
  • Your question is not exactly clear – Ankit Srivastava Jan 12 '16 at 13:30
  • I don't know how to fill and transfer login and pass data to server background in app. – Maria Jan 12 '16 at 14:27
  • It depends on how you configure the server. Usually we use `Basic access authentication` which we put in the header – youssman Jan 12 '16 at 14:55
  • @YHaiti we made Basic access authentication but app doesn't work. I try to do NSURLSession with credentials but 401 still appears:( – Maria Jan 22 '16 at 06:52
  • @Maria can you share your code ? So we can see how do you use the NSURLSession – youssman Jan 22 '16 at 13:01
  • Thank you, @YHaiti. I refreshed my question with code. – Maria Jan 25 '16 at 14:30
  • @Maria I suspect that the problem may come from your server configuration. See [here](http://stackoverflow.com/questions/12701085/what-is-the-realm-in-basic-authentication) may be you're in this case – youssman Jan 28 '16 at 11:03
  • Thank you, @YHaiti, we check. And is it normally that I transfer 2 different pairs login/pass: one for server and another for mssql? – Maria Jan 28 '16 at 11:55
  • @Maria what I usually do is sending only the user credentials and the server store mssql credentials and handle the database connection. – youssman Jan 28 '16 at 12:52
  • @YHaiti just we have different access level. For server it is common (only 1 or 2 login/pass for all users) and for database it is individual. May be I have incomplete php? I describe there only login/pass for database. – Maria Jan 28 '16 at 13:28
  • @Maria I can't tell if you have incomplete PHP, but I bet on that ^^ – youssman Jan 29 '16 at 10:59
  • Thank you for help, @YHaiti! I add my php code to question. – Maria Feb 02 '16 at 08:28

0 Answers0