Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/wix/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 针对api的NSURLSession身份验证_Ios_Objective C_Basic Authentication_Nsurlsession - Fatal编程技术网

Ios 针对api的NSURLSession身份验证

Ios 针对api的NSURLSession身份验证,ios,objective-c,basic-authentication,nsurlsession,Ios,Objective C,Basic Authentication,Nsurlsession,我正在尝试访问网页以检索JSON数据。 当我通过浏览器访问页面时,它会显示一个小框,上面写着需要身份验证。网站正在请求用户名和密码,上面写着:“API”“ 我试图将这些数据传递到NSdictionary对象。 我发现我对HTTP请求的响应是“401-未经授权:由于凭据无效,访问被拒绝。您没有使用您提供的凭据查看此目录或页面的权限” 仅供参考,我在请求的授权标头中传递了用户名和密码 但是我在浏览器中找到了它需要的东西 WWW-Authenticate:Basic realm=“API”在获取或显示

我正在尝试访问网页以检索
JSON数据
。 当我通过浏览器访问页面时,它会显示一个小框,上面写着需要身份验证。网站正在请求用户名和密码,上面写着:
“API”“

我试图将这些数据传递到
NSdictionary
对象。 我发现我对HTTP请求的响应是“401-未经授权:由于凭据无效,访问被拒绝。您没有使用您提供的凭据查看此目录或页面的权限”

仅供参考,我在请求的授权标头中传递了用户名和密码

但是我在浏览器中找到了它需要的东西
WWW-Authenticate:Basic realm=“API”
在获取或显示数据之前

我查找了一个解决方案,我询问了
NSURLCredential
,因此我实现了
NSURLsession
委托
,以触发其功能(

) 但从来没有人叫过我不知道为什么

我该怎么办

这是我的代码:

+(void)getUsername:(NSString*)username andPassword:(NSString*)password completionBlock:(void(^)(NSDictionary* response))completion
{

    NSString *authStr = [NSString stringWithFormat:@"%@:%@", username, password];
    NSData *authData = [authStr dataUsingEncoding:NSUTF8StringEncoding];

    NSString *base64String = [authData base64EncodedStringWithOptions:0];

    NSString *authValue = [NSString stringWithFormat:@"Basic %@", base64String];

    __block NSDictionary *currentUserdictionarytest = nil;
    NSDictionary *headers = @{ @"authorization": authValue,
                               @"accept": @"application/json",
                               @"accept": @"text/html",
                               @"cache-control": @"no-cache",
                               @"postman-token": @"0a47efb3-c559-c0f9-8276-87cbdbe76c9d" };

    NSString *url = @"http://demo.redmine.org/";
stringByAppendingString:@"users/current.json"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]
                                                           cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                       timeoutInterval:10.0];
    [request setHTTPMethod:@"GET"];
    [request setAllHTTPHeaderFields:headers];

    NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];

    NSURLSession *session = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: self delegateQueue:nil]; //[NSOperationQueue mainQueue]]; //[NSURLSession sharedSession];
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
                                                completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                                                    if (error) {
                                                        NSLog(@"%@", error);

                                                    } else {
                                                        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
                                                        NSLog(@"%@", httpResponse);
                                                        NSError *JSONError = nil;
                                                        currentUserdictionarytest = [NSJSONSerialization JSONObjectWithData:data
                                                                                                                options:0
                                                                                                                  error:&JSONError];
                                                        NSLog(@"Printing current user data: %@", data);
                                                        NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                                         NSLog(@"Printing current user data string: %@", str);


                                                        if (JSONError)
                                                        {
                                                            NSLog(@"Serialization error: %@", JSONError.localizedDescription);
                                                        }
                                                        else
                                                        {
                                                            NSLog(@"Response: %@", currentUserdictionarytest);
                                                        }
                                                    }

                                                }];
    [dataTask resume];
}

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler
{
    NSLog(@"did receive challenge method called with task");
    NSString* username = @"username";
    NSString* password = @"password";
    if ([challenge previousFailureCount] == 0) {

        NSURLCredential *newCredential;
        newCredential = [NSURLCredential credentialWithUser:username
                                                   password:password
                                                persistence:NSURLCredentialPersistenceNone];
        [[challenge sender] useCredential:newCredential
               forAuthenticationChallenge:challenge];

    } else {
        [[challenge sender] cancelAuthenticationChallenge:challenge];
    }
}

这是错误的委托方法。会话委托只处理连接级身份验证,例如验证服务器TLS证书或提供客户端证书,而不处理请求级身份验证(例如密码)。您想要
URLSession:task:didReceiveChallenge:completionHandler:

这是错误的委托方法。会话委托只处理连接级身份验证,例如验证服务器TLS证书或提供客户端证书,而不处理请求级身份验证(例如密码)。您需要
URLSession:task:didReceiveChallenge:completionHandler:

您需要传递您的实际用户名和密码,该用户名和密码被授权访问此页面,但您的代码没有问题。我知道,当管理员用户请求此数据时,我的代码工作正常,但当普通用户请求提供的数据时401“错误。我已经阅读了有关使用NSURLProtectionSpace的内容,但我不知道在哪里传递此对象或在哪里使用它。您可以查看此帖子。这可能会有所帮助。我做了正确的事情,我为initWithHost:@“example.com”端口分配了值:80协议:@“http”领域:@“API”“authenticationMethod:nsurAuthenticationMethodHttpBasic];但它还是给了我同样的错误!您需要传递授权访问此页面的实际用户名和密码,除非您的代码没有问题。我知道,当管理员用户请求此数据时,我的代码工作正常,但当普通用户请求此数据时,它给出了“401”错误。我读过关于使用NSURLProtectionSpace的文章,但我不知道在哪里传递这个对象,也不知道在哪里使用它。你可以查看这篇文章。这可能会有帮助。我做了正确的事情,我为initWithHost分配了值:@“example.com”端口:80协议:@“http”领域:@“API”身份验证方法:nsurAuthenticationMethodHttpBasic];但它还是给了我同样的错误!
+(void)getUsername:(NSString*)username andPassword:(NSString*)password completionBlock:(void(^)(NSDictionary* response))completion
{

    NSString *authStr = [NSString stringWithFormat:@"%@:%@", username, password];
    NSData *authData = [authStr dataUsingEncoding:NSUTF8StringEncoding];

    NSString *base64String = [authData base64EncodedStringWithOptions:0];

    NSString *authValue = [NSString stringWithFormat:@"Basic %@", base64String];

    __block NSDictionary *currentUserdictionarytest = nil;
    NSDictionary *headers = @{ @"authorization": authValue,
                               @"accept": @"application/json",
                               @"accept": @"text/html",
                               @"cache-control": @"no-cache",
                               @"postman-token": @"0a47efb3-c559-c0f9-8276-87cbdbe76c9d" };

    NSString *url = @"http://demo.redmine.org/";
stringByAppendingString:@"users/current.json"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]
                                                           cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                       timeoutInterval:10.0];
    [request setHTTPMethod:@"GET"];
    [request setAllHTTPHeaderFields:headers];

    NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];

    NSURLSession *session = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: self delegateQueue:nil]; //[NSOperationQueue mainQueue]]; //[NSURLSession sharedSession];
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
                                                completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                                                    if (error) {
                                                        NSLog(@"%@", error);

                                                    } else {
                                                        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
                                                        NSLog(@"%@", httpResponse);
                                                        NSError *JSONError = nil;
                                                        currentUserdictionarytest = [NSJSONSerialization JSONObjectWithData:data
                                                                                                                options:0
                                                                                                                  error:&JSONError];
                                                        NSLog(@"Printing current user data: %@", data);
                                                        NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                                         NSLog(@"Printing current user data string: %@", str);


                                                        if (JSONError)
                                                        {
                                                            NSLog(@"Serialization error: %@", JSONError.localizedDescription);
                                                        }
                                                        else
                                                        {
                                                            NSLog(@"Response: %@", currentUserdictionarytest);
                                                        }
                                                    }

                                                }];
    [dataTask resume];
}

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler
{
    NSLog(@"did receive challenge method called with task");
    NSString* username = @"username";
    NSString* password = @"password";
    if ([challenge previousFailureCount] == 0) {

        NSURLCredential *newCredential;
        newCredential = [NSURLCredential credentialWithUser:username
                                                   password:password
                                                persistence:NSURLCredentialPersistenceNone];
        [[challenge sender] useCredential:newCredential
               forAuthenticationChallenge:challenge];

    } else {
        [[challenge sender] cancelAuthenticationChallenge:challenge];
    }
}