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();
}
}
?>