snapmate
snapmate

Reputation: 31

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=*

Upvotes: 3

Views: 17419

Answers (2)

野村正法
野村正法

Reputation: 1

A considerable amount of time has passed since the question was asked, but I stumbled upon the same issue and found a solution, so I am posting it.

In my case, it was a matter of the order of enabling the middleware.

Follows are in Program.cs.

Error:

app.UseAuthentication();
app.UseAuthorization();

app.UseCors("MyPolicy");

Success:

app.UseCors("MyPolicy");

app.UseAuthentication();
app.UseAuthorization();

Upvotes: 0

Venantius
Venantius

Reputation: 2539

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.

Upvotes: 0

Related Questions