首页 文章

如何配置HTTP标头进行身份验证? [重复]

提问于
浏览
0

这个问题在这里已有答案:

我是新手使用HTTP,因为我传统上只是前端开发人员,但根据我目前的 Contract ,我被要求使用REST API从服务器提取数据 . 我需要在HTTP标头中使用API密钥和API用户名对自己进行身份验证,并且根据API文档,我要求在“标记”标头中执行此操作 .

我可以获得有关如何格式化_2533123来完成此任务的任何帮助吗?我完全迷失在这里 .

以下是我引用的API文档的具体部分:

REST-APIUser-Token与帐户关联的APIKey和APIUserName必须在令牌标头中以Base64String格式设置为“REST-APIUser - Token”,如下图所示:Convert.ToBase64String(Encoding.UTF8.GetBytes(string . 格式(“{0}:{1}”,APIKey,APIUserName)))其中,APIKey - 与API帐户关联的唯一键APIUserName - 与API帐户关联的UserName当前登录的用户ID ID用户必须在标头中以Base64String格式设置为“APP-User-ID” . Convert.ToBase64String(Encoding.UTF8.GetBytes(AppUserID))其中,AppUserID - 与API应用程序用户关联的用户ID

我拥有 .

2 回答

  • 3

    Add HTTP Header to NSURLRequest

    /* Create request variable containing our immutable request
     * This could also be a paramter of your method */
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.stackoverflow.com"]];
    
    // Create a mutable copy of the immutable request and add more headers
    NSMutableURLRequest *mutableRequest = [request mutableCopy];
    [mutableRequest addValue:@"__usersKey__" forHTTPHeaderField:@"token"];
    
    // Now set our request variable with an (immutable) copy of the altered request
    request = [mutableRequest copy];
    
    // Log the output to make sure our new headers are there    
    NSLog(@"%@", request.allHTTPHeaderFields);
    

    请注意,如果您的意思是HTTPS,则连接是需要身份验证的连接,而不是请求;虽然你似乎没有使用HTTPS .

    NSString * AppUserId = Convert.ToBase64String(Encoding.UTF8.GetBytes(AppUserID))//或者无论你需要什么功能,这看起来都不像Objective-C .

    查看How to Base64 encoding on the iPhone或base64的喜欢 . 这篇文章建议https://github.com/nicklockwood/Base64/

    如果使用该库,则需要类似函数的东西

    - (NSString *)base64EncodedString;
    

    并将其传递给API文档中描述的信息 . 我们无法帮助您,因为我们没有您的所有信息 .

    例如,您可能想要:

    NSString *token = [NSString stringWithFormat@"%@:%@",APIKey,APIUserName]
     NSString *token64 = [token base64EncodedString]; //Assuming that's how you call the library's function. I have never used it so I don't know if it modifies NSString or what. You can always write a function for this part.
    
    [mutableRequest addValue:@"APIUser--Token" forHTTPHeaderField:token64]; //Not sure what the API says the value should be, formatting isn't clear
    
    //Follow the same lines for NSString *AppUserId
    [mutableRequest addValue:@"APP-User-ID" forHTTPHeaderField:AppUserId];
    

    只需按照那里的API以相同的方式执行令牌(以相同的方式生成令牌) .

  • 0

    NSMutableURLRequest 开始,使用 addValue:forHTTPHeaderField:setAllHTTPHeaderFields: 方法根据文档中显示的 Headers 名称添加字段 .

相关问题