Error Domain=NSPOSIXErrorDomain Code=100 "Protocol error" - ios

I am trying to call a service using Alamofire using a .get method.
The request has nothing special no parameters just an Authorization header.
I am going a bit mad here because to request works fine when I run it on postman with the same URL and Authorization token, but when I run my app code with Alamofire it returns this error:
Error Domain=NSPOSIXErrorDomain Code=100 "Protocol error" UserInfo={NSErrorPeerAddressKey={length = 16, capacity = 16, bytes = 0x100201bbd83ad0b10000000000000000}, _kCFStreamErrorCodeKey=100, _kCFStreamErrorDomainKey=1}
I am using:
Alamofire.request("https://myserverURL", method: .get, parameters: [:], encoding: JSONEncoding.default, headers: ["Authorization":"myToken"])
.responseJSON {response in
guard response.result.error == nil else {
//HERE IS WHERE IS GOING IN WITH THE ERROR
}
}
Any thoughts will be much appreciated or point me in the right direction :)

I got exact same error as yours in Cocoa with foundation class URLSession. After hours debugging the issue lies in the HTTP request body.
You should really try to dump the HTTP request/response body to see if there are some malformed fields. For example, Content-Length and Content-Type are right or missing? In my experience if these required(fundamental) headers are malformed, it may not work depending on your OS or other intermediate network accept(e.g. proxy, gateway, server, etc.)
My fault is misplacing function params in the method URLRequest.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type"), which ends up with a wrong Content-Type HTTP field.
However, it works in macOS 10.12 but not 12.11 so you should makes sure your HTTP Request body is not malformed.
Hope it helps.
Form your sample code, I guess the encoding: JSONEncoding.default is wrong. Since an HTTP GET method has NO body, a strict/not-robust network component would reject/not understand it.
What your goal is set the Accept: application/json in the request header, however it's not required if you're sure the response body type.

I got this error with Apache sending an upgrade header. Here is a link to Apache's bugzilla discussion on the issue.
Fixed it by adding Header unset Upgrade to host config in Apache.

This was a tricky one at least for me for an entire day 😅. I figure out at the end how to solve it, it was an HTTP protocol version issue with the server.
We were using IIS to connect to a development API and by default IIS if I remember correctly above 10 use HTTP 2.0 if both the client and the server support it. Also, our server was using an SSL certificate for the development API so I think this was the main issue combined with HTTP 2.0. Disabling the use of HTTP 2.0 for the IIS in the development API fixes the issue.
So my advice is to try to monitor the incoming request to see which kind of protocol is using the request in the server, you can do it with Charles or any another HTTP monitor tool.
I hope this helps someone else with the same problem.

Adding ["Content-Type": "application/json"] to the headers helped.

If you are using some kind of sniffer, try to turn it off.
Running Charles was the reason of this error for me. I was uploading files to the server, and it worked only for small files (several kb). 500kb file leads me to "EOF" failure in Charles, and to your error in xCode. Turning off Charles allowed to upload any large file. I didn't find the exact reason of this yet.
Charles worked well with the same query via Web, but not with iOS.

I have worked with apache server, I have fixed issue by adding Upgrade key in header.
Example:
let headers = ["Upgrade":"h2,h2c", "Content-Type":"application/json"]
Hope it will help other.

try to replace this parameters: [:] with parameters: nil in your request. Strangely it fixed the problem.

I had the same issue fixed it by replacing Authorization feild value to nil instead of ""
[request setValue: #"" forHTTPHeaderField:#"Authorization"];
changed it to this
[request setValue: nil forHTTPHeaderField:#"Authorization"];

In some cases, you must add an entry to ignore the header containing "Upgrade" as shown in this solution: https://forum.directadmin.com/showthread.php?t=55803
And
https://serverfault.com/questions/937253/https-doesnt-work-with-safari
In some cases it was only necessary to add a line in htaccess
Header unset Upgrade
I hope I helped you

In my case there were several F5 balancers in the test network. One of the F5 servers were validating the request incorrectly in such a way that json's objects containing # or / were considered malformed. The issue was hard to detect because many times it was working for me, but few times it was not - exactly according to the specific misconfigured F5 server that my client app was communicating with.

I had this problem when I used Google Places API, then I figured it out the problem was HTTP body, I set my HTTP body to nil and the problem solved

After spending hours the fix was adding "Upgrade" field in header.
let headerFields = ["Upgrade":"h2,h2c","Content-Type":"application/x-www-form-urlencoded"]

I just had a similar issue and resolved it by renaming the authentication header from firebase_token to auth.
I'm building both the backend and the frontend, so it's a reasonable solution.
It looks like the Nginx proxy was cutting off all the unknown headers.

Related

IIS 10.0 adding disallowed headers to responses on API calls

I have an IIS 10.0 server, and I'm seeing that some disallowed headers [Pragma, Expires] are still getting added, but they are only being added to API endpoints, not when static content is getting retrieved. These headers are not being set in the code. I've followed the recommended approach to remove the headers from IIS (adding the remove element to configuration\system.webServer\httpProtocol\customHeaders), and when debugging, I do not see these headers in the HTTP response before it gets sent back to the caller. I would like to remove these headers from the response, but have no idea how to figure out where they are being set. Any pointers?
To extend the comment above.
The key to troubleshoot such issues is to know the source of such headers, so enabling Failed Request Tracing is the quickest way.
If you find that the headers (such as ASP.NET and so on) are set by IIS default modules, you know that you should refer to IIS documentation to locate the settings and turn them off.
In your case, FRT reveals the headers come from a third party module, so you will need to check what settings the vendor provides in documentation.
Note that even if you cannot find vendor settings to turn them off, you might still be able to remove them in several ways such as removing such headers in URL Rewrite outbound rules.

Are you trying to open an SSL connection to a non-SSL Puma?

After working on getting a new project to work, I found that for some reason I couldn't start my rails server. I kept getting the following error:
HTTP parse error, malformed request: #<Puma::HttpParserError: Invalid HTTP format, parsing fails. Are you trying to open an SSL connection to a non-SSL Puma?>
I was able to solve this problem by clearing my browsing history, cookies and saved images.
Click ...
More tools
Clear Browsing Data
Delete everything since the beginning of time.

FineUploader Status 406 ASP.NET

I'm using fineuploader in a ASP.NET Web Application in order to upload files. The uploads are working in most cases. The problem is that the upload of a few files is not working, I'm getting status code 406 when the client sends the post request with the file's chunck.
I tried sending files with the same name,similar size and extension as the files that are not working and they worked so it doesnt seem to be an issue with the filename,size or extension.I couldn't find something in common between these files.
I configured the chunck size for 5MB but also tried chaging to 2 MB and 10MB but they also didn't work.
Here is print of the request, can someone identify the problem and how to solve it?
From the requests, it seems to be some problem with the cloudfront or IIS? I don't know much about this.
Edit:
Looking at the IIS logs I found this, it seems the user is '-' for the request that returned 406, is the cs-username '-' because of the 406 or is the request 406 because of the cs-username '-'? If it's the second, what could make the user be lost like this?
The error message 406 means either the mime type in your Accept request header is invalid for IIS or IIS server can't return data via the type in Accept header.
So please check whether IIS->World wide web services->Static Content has been installed. Please ensure the type in Accept header is also valid in IIS manager->site node->Mime Types.
Now that your client only accept application/json, please ensure your your code will return the correct reponse type.
If that's not working, please enable failed request tracing and post detail error messages in the FRT log.
https://learn.microsoft.com/en-us/iis/troubleshoot/using-failed-request-tracing/troubleshoot-with-failed-request-tracing

AWS API Gateway {"error": "missing authentication token"}

I've been constantly getting the "missing authentication token" error when I click the AWS API gateway POST method url through the browser. I set "AUTH" as none and it's working totally fine through Postman but not with the browser. The problem is that I'm using swift to trigger the method and it doesn't seem to be reaching the gateway at all (no log on CloudWatch) and I don't think my code is wrong (or maybe it is). If someone could point out what my mistake is or a solution to this problem I'd appreciate it so much.
P.S. My lambda function is working totally fine and I typed in the right URL (one in the code is just for example)
Here's my code:
func postNonceToServer(paymentMethodNonce: String) {
let paymentURL = URL(string: "https://example-url.us-east-1.amazonaws.com/prod/create-transaction")!
var request = URLRequest(url: paymentURL)
request.httpBody = "\(paymentMethodNonce)".data(using: String.Encoding.utf8)
request.httpMethod = "POST"
}
In my opinion, this should be a problem in the URL itself. I can think of:
1- Please make sure that the URL is parsed correctly by printing it to the console and pasting it into the browser URL bar. (I have no idea about swift)
2- Make sure that "execute-api" is included in your "example-url", i.e., before the region.
3- Make sure that OPTIONS method has AUTH as none.
Good luck!
After enabling CORS on my endpoints I was receiving the same error message:
{"message":"Missing Authentication Token"}
Everything checked out, but I consistently received that error. To fix my issue I had to deploy the API. To do that, do the following:
Go to "Amazon API Gateway" console
Click on the API Gateway in question
Click "Resources" and select the root resource, e.g., "/"
Click "Actions" and then "Deploy API"
Select the stage you want to deploy to
Click "Deploy"
Long story short, redeploy the API after you've enabled CORS.
This mostly would be because of CORS issue.
Please enable CORS in you API gateway like below. After enabling CORS please redeploy the API
If you don't have OPTIONS added, please follow below steps (If OPTIONS already there just add CORS),
Create a new OPTIONS method under the /services resource
Create and populate the Access-Control-Allow-Origin/Method/Headers in the OPTIONS method.
Enable CORS like below after creating OPTIONS

Impossible to cross site ajax api calls in a chrome extension?

I am trying to create a chrome extension that calls my rails app's api. currently the api returns json and it works fine, however when I try to build it into a chrome extension, it says :
Refused to load script from 'http://mysite.com/demo?q=hello?callback=jQuery16409466155741829425_1342489669670&_=1342489677171' because of Content-Security-Policy.
I looked up the document http://code.google.com/chrome/extensions/contentSecurityPolicy.html and it sounds like I can't do this unless I implement my site into a https version. (under "Relaxing the default policy" section) I am not sure if I understood correctly and it feels ridiculous to make such a big change just because of this. Am I misunderstood? Or is there a workaround to this? Thank you.
In a Chrome extension, cross-site XMLHttpRequests are allowed, provided that you define the source in the manifest file - see http://code.google.com/chrome/extensions/xhr.html.
A JSONP implementation loads an external script using the <script> tag, and inserts it in the document. Unless the source is whitelisted through the "content_security_policy" entry, JSONP cannot be used when manifest version 2 is active (do not use manifest v1 to overcome this, because it's deprecated, and a suitable alternative already exist).
When you're unable to receive a JSON response instead of JSONP, use an ordinary request to fetch the data, cut off the callback, then parse it. Eg:
// response is the response from the server
// Received through `XMLHttpRequest`, jQuery.ajax, or whatever you used
// cuts of jQuery....( and the trailing )
response = response.replace(/^[^(]*\(/, '').replace(/\);?$/, '');
By default browsers do not allow this because of the same origin policy.
However you can get around this by making a jsonp request.
As you using jquery this super easy with getJSON method

Resources