2016-10-07 56 views
0

我有應用程序將使用API​​調用的iPhone應用程序。 我做了用戶名/密碼成功調用與NSURLSession,並接收來自服務器令牌....NSURLSession將令牌發送回服務器獲取數據

NSString *username = @"admin"; 
NSString *password = @"test"; 
NSString *authString = [NSString stringWithFormat:@"%@:%@", 
         username, 
         password]; 

// 2 - convert authString to an NSData instance 
NSData *authData = [authString dataUsingEncoding:NSUTF8StringEncoding]; 

// 3 - build the header string with base64 encoded data 
NSString *authHeader = [NSString stringWithFormat: @"Basic %@", 
         [authData base64EncodedStringWithOptions:0]]; 

// 4 - create an NSURLSessionConfiguration instance 
NSURLSessionConfiguration *sessionConfig = 
[NSURLSessionConfiguration defaultSessionConfiguration]; 

// 5 - add custom headers, including the Authorization header 
[sessionConfig setHTTPAdditionalHeaders:@{ 
              @"Accept": @"application/json", 
              @"Authorization": authHeader 
              } 
]; 

// 6 - create an NSURLSession instance 
NSURLSession *session = 
[NSURLSession sessionWithConfiguration:sessionConfig delegate:self 
         delegateQueue:nil]; 

// 7 - create an NSURLSessionDataTask instance 
NSString *urlString = @"http://test.myserver.am/api/authentication/Login?username=admin&password=test"; 
NSURL *url = [NSURL URLWithString:urlString]; 
NSURLSessionDataTask *task = [session dataTaskWithURL:url 
            completionHandler: 
           ^(NSData *_Nullable data, NSURLResponse *_Nullable response, NSError *_Nullable error) { 
            if (error) 
            { 
             // do something with the error 

             return; 
            } 

            NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response; 
            if (httpResponse.statusCode == 200) 
            { 
             arrTokenData = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error]; 

             [self getDomain]; 
            } else { 
             // failure: do something else on failure 
             NSLog(@"httpResponse code: %@", [NSString stringWithFormat:@"%ld", (unsigned long)httpResponse.statusCode]); 
             NSLog(@"httpResponse head: %@", httpResponse.allHeaderFields); 

             return; 
            } 
           }]; 

// 8 - resume the task 
[task resume]; 

我現在用的令牌從服務器接收和撥打另一個電話獲取用戶數據......

[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES]; 

     NSString *authValue = [arrTokenData valueForKey:@"Token"]; 

     //Configure session with common header fields 
     NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration]; 
     sessionConfiguration.HTTPAdditionalHeaders = @{@"bearer": authValue}; 

     NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration]; 

     NSString *url = @"http://test.myserver.am/api/mobile/LookUps/getuserdata"; 
     NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]]; 

     NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { 
      [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO]; 
      if (!error) { 
       NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response; 
       if (httpResponse.statusCode == 200) 
       { 
        NSDictionary *jsonData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers|NSJSONReadingAllowFragments error:nil]; 

        //Process the data 
       } 
      } 

     }]; 
     [task resume]; 

但我接收下面的狀態代碼,....請求沒有得到成功....

的HttpResponse代碼:500 的HttpResponse頭:{ 「緩存控制」=「N鄰高速緩存「; 「Content-Length」= 36; 「Content-Type」=「application/json; charset = utf-8」;日期=「星期四,2016年10月06日12:16:58 GMT」; Expires =「-1」; Pragma =「no-cache」; Server =「Microsoft-IIS/8.5」; 「X-AspNet-Version」=「4.0.30319」; 「X-Powered-By」=「ASP.NET」; }

****請注意相同的API工作正常,從另一個(xamarin APP)平臺.... **

我使用的Objective-C .... IOS10

有我的發送令牌請求是不正確的....?

請幫我.....我首先堅持在這裏從昨天...

回答

1

正如已經提到的,我敢肯定這應該是:

NSString *authValue = [NSString stringWithFormat:@"Bearer %@", 
     [arrTokenData valueForKey:@"Token"]]; 
    sessionConfiguration.HTTPAdditionalHeaders = @{@"Authorization": authValue}; 

隨着中說,一個500錯誤是一個內部服務器錯誤,而不是一個身份驗證錯誤。看起來真正的問題可能與認證無關,並且您的請求本身以某種方式變得不正確,或者服務器端代碼中有一個錯誤讓您不知何故發癢。

此外,您的代碼似乎沒有檢查令牌是否實際存在於響應中,除非您在其他地方執行此操作。

我會開始檢查以確保令牌實際上存在,如果是,則啓用您可以在服務器上啓用的任何調試,並查看日誌以試圖找出導致500錯誤的原因服務器端。很有可能,一旦你看到服務器端實際發生的事情,修復將是顯而易見的。

+0

你好,非常感謝你的回覆。一旦我獲得與服務器的基本通信,我將用所有標準更新我的代碼。也有進步,我怎麼也沒有得到任何錯誤也是狀態碼200,但我可以淨訪問數據.... NSDictionary * jsonData = [NSJSONSerialization JSONObjectWithData:數據選項:NSJSONReadingMutableContainers | NSJSONReadingAllowFragments錯誤:無]; jsonData顯示0條記錄。 – user2813740

+0

這可能很容易缺乏身份驗證。您是否嘗試過運行Charles Proxy來查看驗證頭是否實際發送?這個頭文件通常保留給操作系統使用,所以它可能會被禁止。您可能必須在單個請求中明確指定它,即使您這樣做了,也可能會完全被吃掉,在這種情況下,請嘗試將它作爲X-Authorization發送。 – dgatwood

+0

您好,非常感謝您..我可以與GET通信發送令牌並獲取數據..從.net團隊獲取有關API調用參數ETC的文檔。有些時候數據以字典,數組或內部jsonData =>數據出現時會出現混淆。再一次感謝你。 – user2813740

0

,你不應該在ULR通過用戶名/密碼,在首次認證的呼叫,因爲你已經把它作爲一個標題字段。 URL中的參數不安全。敏感數據應始終使用POST而不是GET方法傳遞。但這不是問題。

嘗試設置在第二次調用這樣的標題字段:

NSString *authorizationHeader = [NSString stringWithFormat: @"Bearer %@", authValue]; 
[sessionConfig setHTTPAdditionalHeaders:@{ 
             @"Accept": @"application/json", 
             @"Authorization": authorizationHeader 
             } 
]; 

基本上,身份驗證頭字段應該是這樣的(從郵遞員): image

注意:我沒有測試/建立我的代碼!

+0

你好,謝謝你的回覆。是的,我已經嘗試過上面的代碼...事實上,我嘗試了3-4種不同的方式...即使使用不同的API,但我從服務器獲得相同的響應.......可能是我的請求不適合發送令牌....我正在使用ios10 ... – user2813740

+0

不,它應該與令牌完全無關。如果您沒有發送令牌或隨機垃圾,服務器應返回401錯誤代碼(未授權),而不是500錯誤。 500錯誤*始終*表示服務器代碼中的錯誤。這意味着某些東西正在崩潰或拋出異常,或者以一種基本上不會發生的方式破壞。 – dgatwood

+0

然而,API可能需要不同類型的請求(例如帶有JSON參數的POST請求),在這種情況下,500錯誤仍然是服務器中的錯誤(它應發送400錯誤請求),但合理的。 – dgatwood

相關問題