Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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=*
like image 496
snapmate Avatar asked Jul 02 '26 17:07

snapmate


1 Answers

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();
like image 60
野村正法 Avatar answered Jul 05 '26 13:07

野村正法



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!