標籤:des style http color io os 使用 java ar
最近公司的同事業餘時間搞了一個內部的類about.me(https://about.me/)的網站Ocelots,想來是一個很洋氣的注意,以後跟客戶介紹公司的時候,直接登入該網站,談到誰的時候,就開啟該人的首頁,照片,經驗,愛好等等什麼的都一清二楚了。我就開始想,如果是這樣的一個工具,沒有移動端多遺憾,因為我們在任何時候,任何場合都有需求要給客戶展示一下團隊成員。
搭建好項目架構之後,遇到的第一個需求就是統一認證, Ocelots使用了Google Oauth2和Mozilla Persona作為網站入口。其認證方式結構如下(僅以Google Oauth2為例,Mozilla Persona 原理相同):
Google Oauth2為同樣提供了對iOS系統的支援,因此,在Ocelots_iOS用戶端上實現一個和Ocelots一模一樣的認證機制,是非常輕鬆的,但是,痛點在於如何統一二者的認證機制?
通過研究Google Oauth2的認證機制,我發現其認證機制如下:
因此,我們可以通過如下的步驟統一Ocelots_iOS用戶端和Ocelots端的認證機制,
1、為Ocelots_iOS註冊應用ID、確保Ocelots_iOS和Ocelots應用的授權範圍一致。
2、為Ocelots的使用者綁定一個authorize_token,通過該token可以擷取到該賬戶在系統中的所有資訊。
3、按如下的方式實現Ocelots_iOS用戶端的認證機制:
代碼如下:
使用Google Oauth2外掛程式調用Google認證介面:
Object-c代碼
- -(void)authThroughGoogle
- {
- NSString *clientId = GOOGLE_CLIENT_ID;
- NSString *clientSecret = GOOGLE_CLIENT_SECRET;
- NSString *scope = GOOGLE_AUTH_SCOPE;
- GTMOAuth2ViewControllerTouch *authViewController = [[[GTMOAuth2ViewControllerTouch alloc] initWithScope:scope clientID:clientId clientSecret:clientSecret keychainItemName:kKeyChainGoogleAuth delegate:self finishedSelector:@selector(viewController:finishedWithAuth:error:)]autorelease];
- NSString *html = @"<html><body bgcolor=white><div align=center>正在進入google登入頁面...</div></body></html>";
- authViewController.initialHTMLString = html;
- [self.navigationController pushViewController:authViewController animated:YES];
- }
得到認證結果之後,從伺服器端擷取Auth Token:
Object-c代碼
- -(void)viewController:(GTMOAuth2ViewControllerTouch *)viewController finishedWithAuth:(GTMOAuth2Authentication *)auth error:(NSError *)error{
- if (error!=nil) {
- NSLog(@"Auth failed!");
- [self showAlertView:[error localizedDescription]];
- }else{
- NSLog(@"Auth successed!: %@", [auth accessToken]);
- NSString *token = [AuthHelper getAuthTokenThroughGoogle:[auth accessToken]];
- if(token != nil){
- [[NSUserDefaults standardUserDefaults] setObject:token forKey:APP_NAME];
- [self goToMainPage];
- }else{
- [self showAlertView:@"Get get the authorize token"];
- }
- }
- }
統一iOS用戶端和伺服器端認證