首页 文章

来自iphone请求的drupal服务的csrf令牌验证失败

提问于
浏览
0

1.是否必要https://www.mysite.com/my_services/user/token获取该令牌,我设置登录呼叫,但其获取错误'csrf token issue'

_299_之前https://www.mysite.com/my_services/user/login使用post paramater用户名和密码

我怀疑是否每次都要调用用户/令牌..获取令牌并在 Headers 中设置x-csrf-token值以用于发布请求 .

  • (void)viewDidLoad {[super viewDidLoad];

NSString * notificationName = @“MTPostNotificationTut”; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(useNotificationWithString :) name:notificationName object:nil]; }

  • (void)didReceiveMemoryWarning {[super didReceiveMemoryWarning];

}

  • (void)viewWillAppear:(BOOL)animated {
NSString *urlString = @"https://www.mysite.com/my_services/user/token.json";


 NSString *urlS = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];


NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlS]cachePolicy:NSURLCacheStorageAllowed timeoutInterval:10.0];
[request setHTTPMethod:@"POST"];

[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];


NSURLResponse *response;
NSError *err;


NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];

NSString *string = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(@"stringFromData = %@",string);

id jsonResponseData = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:nil];

NSLog(@"jsonResponseData = %@",jsonResponseData);

NSDictionary *jsonResponseDict;
if ([jsonResponseData isKindOfClass:[NSDictionary class]]) {
    jsonResponseDict = jsonResponseData;
} else {
    // Error-handling code
}
jsonResponseData = [jsonResponseDict objectForKey:@"d"];
if (jsonResponseData == nil) {

    id jsonExceptioTypeData = [jsonResponseDict objectForKey:@"ExceptionType"];
    if (jsonExceptioTypeData != nil) {
        NSLog(@"%s ERROR : Server returned an exception", __func__);
        NSLog(@"%s ERROR : Server error details = %@", __func__, jsonResponseDict);
    }
}

token = [jsonResponseDict objectForKey:@"token"];
NSLog(@"token = %@",token);


if (token !=NULL) {

    NSString *notificationName = @"MTPostNotificationTut";
    NSString *key = @"token";
    NSDictionary *dictionary = [NSDictionary dictionaryWithObject:token forKey:key];
    [[NSNotificationCenter defaultCenter] postNotificationName:notificationName object:nil userInfo:dictionary];
}

}

  • (void)checkWithServer:(NSString *)urlname jsonString:(NSString *)jsonString {
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlname]cachePolicy:NSURLCacheStorageAllowed timeoutInterval:10.0];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];


NSURLResponse *response;
NSError *err;


NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];

NSString *string = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(@"stringFromData = %@",string);

id jsonResponseData = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:nil];



NSDictionary *jsonResponseDict;
if ([jsonResponseData isKindOfClass:[NSDictionary class]]) {
    jsonResponseDict = jsonResponseData;
} else {

}
jsonResponseData = [jsonResponseDict objectForKey:@"d"];
if (jsonResponseData == nil) {

    id jsonExceptioTypeData = [jsonResponseDict objectForKey:@"ExceptionType"];
    if (jsonExceptioTypeData != nil) {
        NSLog(@"%s ERROR : Server returned an exception", __func__);
        NSLog(@"%s ERROR : Server error details = %@", __func__, jsonResponseDict);
    }
}
NSLog(@"jsonResponseData = %@",jsonResponseDict);
token = [jsonResponseDict objectForKey:@"token"];
NSLog(@"token = %@",token);

}

  • (void)useNotificationWithString:(NSNotification *)notification {
NSString *urlString = @"https://www.mysite.com/my_services/user/login.json";

NSString *urlS = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

NSDictionary *inputData = [[NSDictionary alloc] initWithObjectsAndKeys:
                           @"ranjeet.gholave", @"username",
                           @"ran123", @"password",
                           nil];

NSError *error = nil;
NSData *jsonInputData = [NSJSONSerialization dataWithJSONObject:inputData options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonInputString = [[NSString alloc] initWithData:jsonInputData encoding:NSUTF8StringEncoding];
[self getTokenFromServer:urlS jsonString:jsonInputString];

}

  • (void)getTokenFromServer:(NSString *)urlname jsonString:(NSString *)jsonString {
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlname]cachePolicy:NSURLCacheStorageAllowed timeoutInterval:30.0];
[request setHTTPMethod:@"POST"];
//    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request addValue:token forHTTPHeaderField:@"X-CSRFToken"];

[request setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];



NSURLResponse *response;
NSError *err;


NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSLog(@"responseDataIn Second Method = %@",responseData);


id jsonResponseData = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:nil];

NSLog(@"jsonResponseData = %@",jsonResponseData);


NSDictionary *jsonResponseDict;
if ([jsonResponseData isKindOfClass:[NSDictionary class]]) {
    jsonResponseDict = jsonResponseData;
} else {
    // Error-handling code
}
jsonResponseData = [jsonResponseDict objectForKey:@"d"];
if (jsonResponseData == nil) {

    id jsonExceptioTypeData = [jsonResponseDict objectForKey:@"ExceptionType"];
    if (jsonExceptioTypeData != nil) {
        NSLog(@"%s ERROR : Server returned an exception", __func__);
        NSLog(@"%s ERROR : Server error details = %@", __func__, jsonResponseDict);
    }
}

如果我允许cookie然后csrf令牌验证问题来了,当我不允许cookie时,csrf令牌问题不会来....如何解决问题..感谢问候,Ranjeet Gholave

1 回答

  • 1

    我知道这是一个旧线程 . 但你应该看看https://github.com/kylebrowning/drupal-ios-sdk以及AFNetworking . 你真的比你更努力地工作 .

    但要回答您的问题,一旦您登录,CSRF令牌将在用户对象中返回,并且对整个用户会话有效 . 因此,您可以对其进行缓存并使用它,直到用户注销或其会话过期为止 .

    使用Drupal IOS SDK,它非常简单:

    [DIOSUser userMakeSureUserIsLoggedInWithUsername:username
                        andPassword:password
                            success:^(AFHTTPRequestOperation *op, id response) {
                                DLog(@"user: %@", response);
                                [DIOSSession sharedSession].user = response;
    
                                //NOTE: fix for services 3.4+ CSRF Token Validation
                                [[DIOSSession sharedSession] setDefaultHeader:@"X-CSRF-Token" value:response[@"token"]];
    
                                [self saveLoginInfoForUserWithUsername:username andPassword:password];
                                [self processUserInfoWithUser:response];
                                success(response);
                            }
                            failure:^(AFHTTPRequestOperation *op, NSError *err) {
                                failure(err);
                            }
     ];
    

相关问题