統一iOS用戶端和伺服器端認證

來源:互聯網
上載者:User

標籤: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代碼  
  1. -(void)authThroughGoogle  
  2. {  
  3.     NSString *clientId = GOOGLE_CLIENT_ID;  
  4.     NSString *clientSecret = GOOGLE_CLIENT_SECRET;  
  5.     NSString *scope = GOOGLE_AUTH_SCOPE;  
  6.     GTMOAuth2ViewControllerTouch *authViewController = [[[GTMOAuth2ViewControllerTouch alloc] initWithScope:scope clientID:clientId clientSecret:clientSecret keychainItemName:kKeyChainGoogleAuth delegate:self finishedSelector:@selector(viewController:finishedWithAuth:error:)]autorelease];  
  7.     NSString *html = @"<html><body bgcolor=white><div align=center>正在進入google登入頁面...</div></body></html>";  
  8.     authViewController.initialHTMLString = html;  
  9.     [self.navigationController pushViewController:authViewController animated:YES];  
  10. }  



得到認證結果之後,從伺服器端擷取Auth Token: 

Object-c代碼  
  1. -(void)viewController:(GTMOAuth2ViewControllerTouch *)viewController finishedWithAuth:(GTMOAuth2Authentication *)auth error:(NSError *)error{  
  2.     if (error!=nil) {  
  3.         NSLog(@"Auth failed!");  
  4.         [self showAlertView:[error localizedDescription]];  
  5.     }else{  
  6.         NSLog(@"Auth successed!: %@", [auth accessToken]);  
  7.         NSString  *token = [AuthHelper getAuthTokenThroughGoogle:[auth accessToken]];  
  8.         if(token != nil){  
  9.             [[NSUserDefaults standardUserDefaults] setObject:token forKey:APP_NAME];  
  10.             [self goToMainPage];  
  11.         }else{  
  12.             [self showAlertView:@"Get get the authorize token"];  
  13.         }  
  14.     }  
  15. }  

統一iOS用戶端和伺服器端認證

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.