简体   繁体   中英

Request Rest API with Http failed with 401 but Https works

Below codes worked when the Uri = "https://someRestApi" , but reports 401 Unauthorized when Uri = "http://SomeRestApi" , why is it happening? The server is hosted in Azure App Service, with TLS/SSL settings . Sending the http request with Postman does work.

 public static void Main(string[] args)
    {
        var uri = new Uri("http://someTestApiUri.com");

        var token = GetTestToken();
        HttpWebRequest httpRequest = HttpWebRequest.Create(uri) as HttpWebRequest;
        httpRequest.Headers["Authorization"] =  "Bearer " + token.AccessToken;
        using (HttpWebResponse response = httpRequest.GetResponse() as HttpWebResponse)
        {
            //Some logic here...
         
        }
    }

This maybe because the developer of the API may have specified that endpoint allows only https either through the CORS and origin specification or Attribute Filter. by decorating the ApiController to allow only https.

kindly read some of the articles below.

  1. https://jonathancrozier.com/blog/how-to-configure-your-asp-net-web-apps-and-apis-to-require-https

  2. https://www.c-sharpcorner.com/article/how-to-enable-https-in-asp-net-web-api/

there are many articles that will give you a clue but these are just few so it is not exhaustive.

so if the backend or whoever developed the endpoint specifies that only https endpoint should be hit, when you attempt to hit the http he may return the message or http statusCode 401. again read more about http status code and what they mean.

Also, it may work in postman because you disabled a security settings on your postman. please try and use a secure channel when making API calls.

Thanks.

Regards

Authentication and authorization in Azure App Service and Azure Functions in the section about disabling requireHttps clearly states:

However, we do recommend sticking with HTTPS, and you should ensure no security tokens ever get transmitted over non-secure HTTP connections..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM