做一個問答系統的手機客戶端,第一件要解決的就是與伺服器溝通取資料,而溝通的起點是登入驗證。以下記錄整個串接過程,技術點為:ASIHttpRequest 網路庫、Toast 提示框、MD5 加密。
appKey:F0D71CBA8E2D....470A1F33AD457
介面位址: https://uc.gongzuohou.cn/index.php/api/user/login,方法 POST。
上行參數:
uname (string):使用者名稱upwd (string):使用者密碼,傳 md5(upwd)sign (string):校驗碼,產生方式為 md5(uname . upasswd . appKey)下行欄位:
errno:狀態碼,0 代表成功,>1 代表失敗error:回傳訊息uid / uname:僅在登入成功時回傳注意 sign 的計算方式:先對密碼做 MD5,再將「帳號 + 已加密的密碼 + appKey」串接後再做一次 MD5。兩段加密用的是同一個結果,順序不能顛倒,否則伺服器驗不過。
#import <UIKit/UIKit.h>
#import "ASIHttpHeaders.h"
#import "tooles.h"
@interface MainViewController : UIViewController <NSURLConnectionDataDelegate>
{
UITextField *username;
UITextField *password;
}
@property (nonatomic, retain) UITextField *username;
@property (nonatomic, retain) UITextField *password;
@property (nonatomic, retain) NSString *md5pwd;
@property (nonatomic, retain) NSString *md5str;
@property (retain, nonatomic) NSData *data;
@end
#import "MainViewController.h"
#import "MyMD5.h"
#define URL @"https://uc.gongzuohou.cn/index.php/api/user/login"
#define appKey @"F0D71CBA8E2D.....470A1F33AD457"
@interface MainViewController ()
- (void)login:(id)sender;
- (void)GetErr:(ASIHTTPRequest *)request;
- (void)GetResult:(ASIHTTPRequest *)request;
@end
@implementation MainViewController
@synthesize username, password;
- (void)login:(id)sender {
// 表單送出前的驗證
if (username.text == nil || password.text == nil) {
[tooles MsgBox:@"用戶名或密碼不能為空!"];
return;
}
[username resignFirstResponder]; // 收起鍵盤
[password resignFirstResponder];
[tooles showHUD:@"正在登陸...."];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:URL]];
_md5pwd = [MyMD5 md5:password.text];
NSString *s = [[NSString alloc] initWithFormat:@"%@%@%@",
username.text, _md5pwd, appKey];
_md5str = [MyMD5 md5:s];
// 設定表單欄位
[request setPostValue:username.text forKey:@"uname"];
[request setPostValue:_md5pwd forKey:@"upwd"];
[request setPostValue:_md5str forKey:@"sign"];
[request setDelegate:self];
[request setDidFinishSelector:@selector(GetResult:)];
[request setDidFailSelector:@selector(GetErr:)];
[request startAsynchronous];
}
// 請求成功
- (void)GetResult:(ASIHTTPRequest *)request {
[tooles removeHUD];
NSString *str = [request responseString];
NSLog(@"-------\n%@", str);
_data = [request responseData];
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:_data
options:NSJSONReadingMutableContainers
error:nil];
NSString *sname = [dic objectForKey:@"username"];
NSLog(@"name:%@", sname);
int flag = [[dic objectForKey:@"errno"] intValue];
if (flag == 0) {
[tooles MsgBox:@"登陸驗證成功"];
} else if (flag == 1) {
[tooles MsgBox:@"用戶名或密碼錯誤"];
}
}
// 連線失敗
- (void)GetErr:(ASIHTTPRequest *)request {
[tooles removeHUD];
[tooles MsgBox:@"網絡錯誤,連接不到服務器"];
}
- (void)viewDidLoad {
[super viewDidLoad];
UILabel *txt1 = [[UILabel alloc] initWithFrame:CGRectMake(30, 90, 70, 30)];
[txt1 setText:@"用戶名"];
[txt1 setBackgroundColor:[UIColor clearColor]];
[self.view addSubview:txt1];
UILabel *txt2 = [[UILabel alloc] initWithFrame:CGRectMake(30, 140, 70, 30)];
[txt2 setText:@"密 碼"];
[txt2 setBackgroundColor:[UIColor clearColor]];
[self.view addSubview:txt2];
username = [[UITextField alloc] initWithFrame:CGRectMake(120, 90, 150, 30)];
[username setBorderStyle:UITextBorderStyleRoundedRect];
[self.view addSubview:username];
password = [[UITextField alloc] initWithFrame:CGRectMake(120, 140, 150, 30)];
[password setBorderStyle:UITextBorderStyleRoundedRect];
[password setSecureTextEntry:YES];
[self.view addSubview:password];
UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[btn setTitle:@"提交" forState:UIControlStateNormal];
[btn addTarget:self action:@selector(login:) forControlEvents:UIControlEventTouchUpInside];
[btn setFrame:CGRectMake(90, 180, 150, 40)];
[self.view addSubview:btn];
}
@end
1. 空值判斷寫錯了。 username.text == nil 幾乎不會成立,因為 UITextField 的 text 預設是空字串而非 nil。應該改用 username.text.length == 0,才真的攔得住空白輸入。
2. 明文傳輸的風險。 整個流程走 http,雖然密碼經過兩段 MD5,但 MD5 早已不適合當密碼雜湊演算法(可彩虹表反查、碰撞已被實證)。伺服器端應改用 bcrypt、scrypt 或 Argon2 並加鹽,傳輸層則務必上 HTTPS。
3. appKey 硬編碼在客戶端等於公開。 任何拿到 ipa 的人都能反編譯取出這個字串,因此它只能當作「延緩濫用」而非真正的安全邊界。真正的防護要放在伺服器的 rate limit 與行為偵測。
4. ASIHttpRequest 已停止維護。 這個庫多年沒有更新,在新版 iOS 上有相容問題。新專案請改用 NSURLSession 或 AFNetworking / Alamofire。
5. JSON 解析要檢查 error。 JSONObjectWithData: 的 error 傳 nil,一旦伺服器回傳非 JSON(例如 502 頁面),dic 會是 nil 而不會崩潰,但後續所有判斷都靜默失效。記得檢查並提示使用者。
6. 登入成功後要保存 session。 範例只跳了一個提示框。實務上應把 uid 與 token 存進 NSUserDefaults 或鑰匙串,並在啟動時驗證,才能真正做到「保持登入」。