搭建好项目框架之后,遇到的第一个需求就是统一认证, 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认证界面:
-(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:
-(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"]; } } }