APP端实现安全认证相关功能总结

2017年6月13日
一.基本原理:通过app端和appServer一套约定(协议)来实现安全认证【主要是在请求header头里面添加制定参数来实现】,实现拦截功能主要在appServer端实现。
1.目的:减轻服务器端攻击概率,防止链接被劫持访问,防止重复提交等。

二.实现
1.主要约定了如下几个key

APP端实现安全认证相关功能总结_第1张图片
image.png

2.常见场景流程图
2.1 app登录流程


APP端实现安全认证相关功能总结_第2张图片
image.png

2.2sign校验过程


APP端实现安全认证相关功能总结_第3张图片
image.png

3.代码实现
3.1相关宏定义
//安全性相关key (header默认会变成小写)
#define server_key  @"salt"  //服务端跟客户端一起约定的特定图片,由特定图片计算出的MD5值(其实是后端给的图片)
#define token_key @"token" //客户端登录成功后服务端返回的安全令牌,用于校验接口访问的合法性,【一般登录成功后,正确情况下都不变】
#define guid_key @"guid" //客户端请求链接唯一参数,类似uuid,每次请求都需要重新获取,每次都不一样类似时间戳的概念
#define submitToken_key @"submittoken" //客户端提交表单的安全令牌;(只有post的时候才提交),防止重复提交用。 header默认会变小写
#define client_sign_key @"sign" //生成规则
#define deviceNumber_key @"devicenumber" //客户端设备号
#define obligateToken_key @"obligatetoken" //服务端预留Token,免登录用

#define apiCode_key  @"apiCode" //过渡版本,区分新老版本用的 值为1后台就校验,以后后台会去掉

3.2请求设置相关header参数

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    //设置header参数
[QQRequest setHeaderParams:param withManager: manager reuestMode:getReqMode];


+ (void)setHeaderParams:(NSDictionary*)param withManager: (AFHTTPRequestOperationManager *)manager reuestMode:(NSString*)mode
{
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:param];
    //设置header参数
    NSString *key = apiCode_key;
    NSString *value = @"1";
    [manager.requestSerializer setValue:value forHTTPHeaderField:key];
    [dic setObject:value forKey:key];
    
    key = guid_key;
    value = [HuConfigration getGuidKey];
    if (value.length > 0) {
        [manager.requestSerializer setValue:value forHTTPHeaderField:key];
        [dic setObject:value forKey:key];
    }
    
    key = token_key;
    value = [kUserDefaults objectForKey:key] ?: @"";
    if (value.length <= 0) {
        value = [kUserDefaults objectForKey:obligateToken_key];
    }
    if (value.length > 0) {
        [manager.requestSerializer setValue:value forHTTPHeaderField:key];
        [dic setObject:value forKey:key];
    }
    
    key = deviceNumber_key;
    value = [[HFDeviceInfo sharedHFDeviceInfo] getDeviceUUID] ?: @"";
    if (value.length > 0) {
        [manager.requestSerializer setValue:value forHTTPHeaderField:key];
        [dic setObject:value forKey:key];
    }

    if ([mode isEqualToString:postReqMode]) {
        key = submitToken_key;
        value = [kUserDefaults objectForKey:key] ?: @"";
        if (value.length > 0) {
            [manager.requestSerializer setValue:value forHTTPHeaderField:key];
            [dic setObject:value forKey:key];
        }
    }
    
    key = client_sign_key;
    NSString *tmp = [HuConfigration getUrlParamsFormatString:dic];
    NSString *serverKey = [HuConfigration getServerKey];
    if (value.length > 0) {
        value = [[NSString stringWithFormat:@"%@&%@=%@", tmp, server_key, serverKey] MD5];
        [manager.requestSerializer setValue:value forHTTPHeaderField:key];
    }
    
//    NSLog(@"wy_sendParam=%@&%@=%@",tmp,server_key,serverKey);
}

+ (NSString *)getGuidKey
{
    NSString *res = [NSUUID UUID].UUIDString;
    return res;
}

- (NSString*)getDeviceUUID
{
    NSString *strUUID = [SSKeychain passwordForService:kSSToolkitTestsServiceName account:kSSToolkitTestsAccountName];
    
    if ([strUUID length] <= 0) {
        CFUUIDRef uuidRef = CFUUIDCreate(kCFAllocatorDefault);
        strUUID = (NSString *)CFBridgingRelease(CFUUIDCreateString(kCFAllocatorDefault, uuidRef));
        [SSKeychain setPassword:strUUID forService:kSSToolkitTestsServiceName account:kSSToolkitTestsAccountName];
    }
    return strUUID;
}

3.3 若回包中headre有新的值,更新

    [manager POST:url parameters:param success:^(AFHTTPRequestOperation *operation, id responseObject) {
        //设置新的header值
        [QQRequest setNewHeaderDataFromResponse:operation];
        [QQRequest handleResponse:responseObject HUD:HUD success:success error:error];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        //设置新的header值
        [QQRequest setNewHeaderDataFromResponse:operation];
    }];

//设置新的header值
+ (void)setNewHeaderDataFromResponse:(AFHTTPRequestOperation *)operation
{
    NSDictionary *responseHeaders = operation.response.allHeaderFields;
    NSString *key = token_key;
    NSString *value = responseHeaders[key];
    if (value.length > 0) {
        [kUserDefaults setObject:value forKey:key];
//        NSLog(@"wy_new_%@=%@",key,responseHeaders[key]);
    }
    
    key = submitToken_key;
    value =  responseHeaders[key];
    if (value.length > 0) {
        [kUserDefaults setObject:value forKey:key];
//        NSLog(@"wy_new_%@=%@",key,responseHeaders[key]);
    }
    
    key = obligateToken_key;
    value =  responseHeaders[key];
    if (value.length > 0) {
        [kUserDefaults setObject:value forKey:key];
//        NSLog(@"wy_new_%@=%@",key,responseHeaders[key]);
    }
}

3.4 安全认证相关参数处理

+ (void)handleResponse:(NSDictionary *)dict
                   HUD:(MBProgressHUD *)HUD
               success:(SuccessBlock)success
                 error:(ErrorBlock)error
{
    Boolean successFlag = [dict[@"success"] boolValue];
    if (!successFlag) {
        
        BOOL needAlertError = [QQRequest handleSecurityError:dict];
        if (needAlertError) {
            NSString *string = dict[@"errMsg"] ? dict[@"errMsg"] : @"网络异常";
            HUD.detailsLabelText = string;
            HUD.detailsLabelFont = [UIFont systemFontOfSize:15 * kFontScale];
            HUD.mode = MBProgressHUDModeCustomView;
            [HUD hide:YES afterDelay:2];
        }
        
        if (error) {
            error(dict);
        }
        
        return;
    }
    if (success) {
        [HUD hide:YES];
        success(dict);
    }
}

//处理安全性相关错误
+ (BOOL)handleSecurityError:(NSDictionary*)dic
{
    BOOL needAlertError = YES;
    
    NSString *errCode = [HuConfigration stringValue:dic[@"errCode"]];
    BOOL needBackToLoginPage = NO;
    if ([errCode isEqualToString:@"api_001"]){
        //submitToken失效,请重新登录
//        needBackToLoginPage = YES;
    }else if ([errCode isEqualToString:@"api_002"]){
        //不是同一设备,请重新登录
        needBackToLoginPage = YES;
    }else if ([errCode isEqualToString:@"api_003"]){
        //sign无效,请重新登录
//        needBackToLoginPage = YES;
    }else if ([errCode isEqualToString:@"api_004"]){
        //guid失效,请重新登录
//        needBackToLoginPage = YES;
    }else if ([errCode isEqualToString:@"api_005"]){
        //非法参数,请重新请求
    }else if ([errCode isEqualToString:@"api_006"]){
        //token失效,请重新请求
        NSString *value = [kUserDefaults objectForKey:obligateToken_key];
        NSDictionary *param = @{obligateToken_key:value};
        NSString *funItem = HuFuncItem_getToken;
        
        NSString *urlString = [NSString stringWithFormat:@"%@/%@",quanQaunURL,funItem];
        [Request requestAppServerCommon:param urlString:urlString view:nil reuestMode:getReqMode funItem:funItem success:^(NSDictionary *dic) {
            //请求失败重新退出登录
            if (dic[@"success"] && [dic[@"success"] boolValue] == NO) {
                [HuConfigration backToLoginPage];
            }
       } error:^(NSDictionary *dic) {
           //请求失败重新退出登录
           if (dic[@"success"] && [dic[@"success"] boolValue] == NO) {
               [HuConfigration backToLoginPage];
           }
           TRACELOG(@"%@",dic[@"errMsg"] ? dic[@"errMsg"] : @"网络异常");
       } failure:^{
           TRACELOG(@"failure");
       }];

    }
    
    if (needBackToLoginPage) {
        [HuConfigration backToLoginPage];
    }
    
    return needAlertError;
}

如果您发现本文对你有所帮助,如果您认为其他人也可能受益,请把它分享出去。

你可能感兴趣的:(APP端实现安全认证相关功能总结)