统一iOS客户端和服务器端认证

      最近公司的同事业余时间搞了一个内部的类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认证界面:
-(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"];
        }
    }
}

猜你喜欢

转载自ningandjiao.iteye.com/blog/1772346