'HTTP Post Request: 401 (Unauthorized)
I have the following problem:
My server responds to an HTTP POST with a 401 error. In the same webapp, I'm able to use an HTTP GET request and that works fine. I tested the POST request with postman and I'm able to get data successfully (so at least it's working)...
Request code (copied from Postman):
var data = JSON.stringify({
"query": {
"objectTypeId": "168"
}
});
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
console.log(this.responseText);
}
});
xhr.open("POST", <here is my url>);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader("crossdomain", "true");
xhr.setRequestHeader("Authorization", "Basic XXXXXXXX");
xhr.send(data);
Most of the threads I found related to this problem are pointing at the CORS configuration, but I think this is working because the get-request works. Anyways, here's the CORS configuration:
web.xml:
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>CORS</filter-name>
<filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>
<init-param>
<param-name>cors.configurationFile</param-name>
<param-value>/WEB-INF/cors.properties</param-value>
</init-param>
</filter>
cors.properties:
cors.allowGenericHttpRequests = true
cors.allowOrigin=*
cors.supportsCredentials = true
cors.supportedMethods=GET, POST, HEAD, PUT, DELETE, OPTIONS
cors.supportedHeaders=*
Solution 1:[1]
This is, in fact, a CORS issue. Your API needs to answer those OPTIONS requests properly otherwise the browser is going to block the request. Relevant external link: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS.
Other people on SO have also provided other, more in-depth answers to this problem. A great long-form answer can be found here.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |