搜索
您的当前位置:首页正文

关于token的处理

来源:二三娱乐

关于token的处理

神盾养车项目,token每两个小时就会失效,那么我们就会经常出现token失效的情况.那么我们就需要处理.现在有两个思路:

  • 在发送请求之前判断token是否失效.如果失效,那么先去刷新token;如果没有失效,那么继续请求.这里我们就需要解析token,来判断token是否超时.
//解析token,判断token是否超时
- (BOOL)analysisToken:(NSString *)token
{
    //1.1 将token分隔成三部分
    NSArray *tokenArr = [token componentsSeparatedByString:@"."];
    //1.2 拿到我要解析的部分(第二部分)
    NSString *tokenStr = tokenArr[1];
    //1.3 解密
    NSData *tokenDecodeData = [[NSData alloc] initWithBase64EncodedString:[tokenStr stringByAppendingString:@"="] options:NSDataBase64DecodingIgnoreUnknownCharacters];
    NSDictionary *tokenDecodeDic = [NSJSONSerialization JSONObjectWithData:tokenDecodeData options:0 error:nil];
    
    //2.4获得过期时间戳
    NSString *expTimeStr = tokenDecodeDic[@"exp"];
    NSTimeInterval expTimeInterval = [expTimeStr integerValue];
    
    //2.5获得当前时间戳
    NSDate *currentDate = [NSDate date];
    NSTimeInterval currentTimeInterval = [currentDate timeIntervalSince1970];
    
    //2.6 获得两个时间戳之间的间隔
    NSInteger timeinteval = (expTimeInterval - currentTimeInterval) / 60 / 60;
    
    if (timeinteval >= 2)
    {
        return YES;
    }
    else
    {
        return NO;
    }
}
  • 根据请求的返回值来判断token是否失效,如果失效,那么先去刷新token,然后重新发送请求.但是,这里会有一个问题,就是怎么能在刷新token之后重新请求,AFN没有直接提供方法,我们可以在task里面拿到请求的各种数据.不过这样重新发送请求会有一次多余的操作,而且在请求中发送请求,感觉不太好,所以放弃了.
    task.originalRequest.HTTPMethod;
    task.originalRequest.HTTPBody;
    task.originalRequest.URL;
Top