這次要串接的Web Service是使用Basic Authentication,是我公司資深工程師所用的認證方式,我之前都是取得伺服器回傳的Token來做之後API呼叫的「令牌」。學一下Basic Authentication也不錯啦~
WiKi這麼描述HTTP基本認證:
在HTTP中,基本認證(Basic access authentication)是一種用來允許網頁瀏覽器或其他用戶端程式在請求時提供使用者名稱和口令形式的身分憑證的一種登入驗證方式。
在傳送之前是以使用者名稱追加一個冒號然後串接上口令,並將得出的結果字串再用Base64演算法編碼。例如,提供的使用者名稱是Aladdin、口令是open sesame,則拼接後的結果就是Aladdin:open sesame,然後再將其用Base64編碼,得到QWxhZGRpbjpvcGVuIHNlc2FtZQ==。最終將Base64編碼的字串傳送出去,由接收者解碼得到一個由冒號分隔的使用者名稱和口令的字串。
雖然對使用者名稱和口令的Base64演算法編碼結果很難用肉眼識別解碼,但它仍可以極為輕鬆地被電腦所解碼,就像其容易編碼一樣。編碼這一步驟的目的並不是安全與隱私,而是為將使用者名稱和口令中的不相容的字元轉換為均與HTTP協定相容的字元集。
PostMan現在可以幫忙產生code,直接複製貼上就能編譯執行耶~
/** Theme: Basic Auth IDE: Xcode 8 Language: Objective C Date: 106/10/27 Author: HappyMan Blog: https://cg2010studio.com/ */ -(void)happyTest { NSDictionary *headers = @{}; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://happystudio/api/token"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0]; [request setHTTPMethod:@"GET"]; [request setAllHTTPHeaderFields:headers]; // Forming string with credentials 'myusername:mypassword' NSString *authStr = [NSString stringWithFormat:@"%@:%@", @"jason.chiu@happystudio.com", @"123456"]; // Getting data from it NSData *authData = [authStr dataUsingEncoding:NSASCIIStringEncoding]; // Encoding data with base64 and converting back to NSString NSString* authStrData = [[NSString alloc] initWithData:[authData base64EncodedDataWithOptions:NSDataBase64EncodingEndLineWithLineFeed] encoding:NSASCIIStringEncoding]; // Forming Basic Authorization string Header NSString *authValue = [NSString stringWithFormat:@"Basic %@", authStrData]; // Assigning it to request [request setValue:authValue forHTTPHeaderField:@"Authorization"]; NSURLSession *session = [NSURLSession sharedSession]; NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { if (error) { NSLog(@"error: %@", error); } else { NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response; NSLog(@"response: %@", httpResponse); } }]; [dataTask resume]; }
真能順利回傳資料呢!
response: { URL: http://happystudio/api/token } { status code: 200, headers {
“Content-Length" = 160;
“Content-Type" = “application/json";
Date = “Thu, 26 Oct 2017 15:55:46 GMT";
Server = “Werkzeug/0.12.2 Python/2.7.13″;
} }
Comments on: "[iOS] Basic Authentication" (1)
[…] 其實就是串API時所發現的奇異問題!使用Postman或Chrome呼叫都很成功回傳我要的資料,卻在寫進iOS中卻得到不預期的結果,先前有提到過Basic Authentication,程式傳遞token後,回傳結果表示沒有傳遞token給server,明明就是照先前的code複製貼上修改API Function名稱,這次居然有問題讓我很納悶。 […]
讚讚