如何使用 "GET" 获取数据并显示 - 授权 header 使用 Rest API

How to fetch data and display using "GET"-with Authorization header using Rest API

我有一个 url 来获取数据和显示。在这里我需要按照一些步骤进行 authAuthorization header: to base64,sha256 0r sha512

所以我在这里编码以在我的控制台中使用授权 header.But 获取数据我收到错误:

str: {
  "error_code": "invalid_auth_header",
  "message": "Invalid authorization. Use an auth header or access hash"
}

我是 HTTP/GET、授权 header 等方面的新手。我做错了什么,我需要更改什么才能解决这个问题?

这是我的代码(这是基于以下答案的更新代码):

 #import "ViewController.h"
 #import <CommonCrypto/CommonDigest.h>

 @interface ViewController ()

 @end

 @implementation ViewController

 - (void)viewDidLoad {
      [super viewDidLoad];
      NSString *userName = @"testingyouonit@gmail.com";
      NSString *password = @"testingyouonit2";

      NSData *plainData = [password dataUsingEncoding:NSUTF8StringEncoding];
      NSString *base64String = [plainData base64EncodedStringWithOptions:0];
      base64String=[self sha256HashFor: base64String];

      //setting the string of the url taking from appliance IP.
      NSString *urlString = @"https://api.exampleURL.com/files";

      NSMutableURLRequest *request= [[NSMutableURLRequest alloc] init];
      [request setURL:[NSURL URLWithString:urlString]];
      [request setHTTPMethod:@"GET"];

      NSString *authStr = [NSString stringWithFormat:@"%@:%@", userName, base64String];
      NSData *authData = [authStr dataUsingEncoding:NSUTF8StringEncoding];
      NSString *authValue = [NSString stringWithFormat:@"Basic %@", [authData base64Encoding]];
      [request setValue:authValue forHTTPHeaderField:@"Authorization"];

      NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

      NSString *str = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];

      NSLog(@"str: %@", str);
}
-(NSString*)sha256HashFor:(NSString*)input {
     const char* str = [input UTF8String];
     unsigned char result[CC_SHA256_DIGEST_LENGTH];
     CC_SHA256(str, strlen(str), result);

     NSMutableString *ret = [NSMutableString stringWithCapacity:CC_SHA256_DIGEST_LENGTH*2];
     for(int i = 0; i<CC_SHA256_DIGEST_LENGTH; i++) {
          [ret appendFormat:@"%02x",result[i]];
     }
     return ret;
}

首先,请修正您代码中的以下错误:

  1. base64String=[self sha256HashFor: password]; 更改为 base64String=[self sha256HashFor: base64String];
  2. NSString *str1 = [NSString stringWithFormat:@"https://api.exampleurl/user/data",userName,base64String];NSString *str1 = [NSString stringWithFormat:@"https://api.exampleurl/user/data"];

之后,要使用基本授权,请使用以下代码:

NSString *authStr = [NSString stringWithFormat:@"%@:%@", userName, base64String];
NSData *authData = [authStr dataUsingEncoding:NSUTF8StringEncoding];
NSString *authValue = [NSString stringWithFormat:@"Basic %@", [authData base64Encoding]];
[request setValue:authValue forHTTPHeaderField:@"Authorization"];