web
You’re offline. This is a read only version of the page.
close
Skip to main content
Community site session details

Community site session details

Session Id :
Microsoft Dynamics CRM (Archived)

Http Status Code (401) was expected in the response

(0) ShareShare
ReportReport
Posted on by

Hello all I am trying to create a native C# application (using the WebAPI) that has been registered with Azure AD. This application will need to create specific entities in the crm but that is almost irrelevant for my question.

I tried using the example the MSDN provided and while it does not throw any run time exceptions, the following message shows:

Microsoft.IdentityModel.Clients.ActiveDirectory Error: 4 : 07/06/2018 15:39:31:  - AuthenticationParameters: System.ArgumentException: Unauthorized Http Status Code (401) was expected in the response

Parameter name: response

While checking the request/response with fiddler I noticed that everything is sent over http and that the response is 502 - bad gateway. Putting this in here in case it helps.

I went back onto MSDN to check what this error code means and I got the following from this webpage: docs.microsoft.com/.../compose-http-requests-handle-errors

401 Unauthorized Expect this for the following types of errors:

- BadAuthTicket
- ExpiredAuthTicket
- InsufficientAuthTicket
- InvalidAuthTicket
- InvalidUserAuth
- MissingCrmAuthenticationToken
- MissingCrmAuthenticationTokenOrganizationName
- RequestIsNotAuthenticated
- TamperedAuthTicket
- UnauthorizedAccess
- UnManagedInvalidSecurityPrincipal

The error *SEEMS* to be bad token, but I might be wrong as I am just a beginner in this sphere for now.

Below is the code inside the main .cs file

using System;

using Microsoft.Crm.Sdk.Samples.HelperCode;
using System.Net.Http;
using System.Net.Http.Headers;

namespace Test
{
    class Program
    {

        private HttpClient httpClient;

        static void Main(string[] args)
        {
            
            Program app = new Program();
            try
            {
                app.ConnectToCRM(args);
            }
            catch (System.Exception ex)
            {
                DisplayException(ex);
            }
            finally
            {
                if (app.httpClient != null)
                { app.httpClient.Dispose(); }
                Console.WriteLine("Press <Enter> to exit the program.");
                Console.ReadLine();
            }
        }


        private void ConnectToCRM(String[] cmdargs)
        {
            Configuration config = null;
            if (cmdargs.Length > 0)
                config = new FileConfiguration(cmdargs[0]);
            else
                config = new FileConfiguration("default");
            Authentication auth = new Authentication(config);
            httpClient = new HttpClient(auth.ClientHandler, true);
            httpClient.BaseAddress = new Uri(config.ServiceUrl + "api/data/v9.0/");
            httpClient.Timeout = new TimeSpan(0, 2, 0);
            httpClient.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0");
            httpClient.DefaultRequestHeaders.Add("OData-Version", "4.0");
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        }

        private static void DisplayException(Exception ex)
        {
            Console.WriteLine("The application terminated with an error.");
            Console.WriteLine(ex.Message);
            while (ex.InnerException != null)
            {
                Console.WriteLine("\t* {0}", ex.InnerException.Message);
                ex = ex.InnerException;
            }
        }

    }
}


And here is the config file used to make a connection:

<?xml version="1.0" encoding="utf-8"?>
<configuration>

  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
  </startup>

  <connectionStrings>
    <clear />

    <!-- When providing a password, make sure to set the app.config file's security so that only you can read it. -->
    <add name="default"   connectionString="Url=https://<tenant>.api.crm11.dynamics.com; Username=user; Password=pass" />
  </connectionStrings>  

  <appSettings>
    <!--For information on how to register an app and obtain the ClientId and RedirectUrl
        values see msdn.microsoft.com/.../mt149065 -->

    <!--Active Directory application registration. -->
    <!--These are dummy values and should be replaced with your actual app registration values.-->
    <add key="ClientId" value="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" />
    <add key="RedirectUrl" value="https://<tenant>.crm11.dynamics.com" />

    <!-- Use an alternate configuration file for connection string and setting values. This optional setting
    enables use of an app.config file shared among multiple applications. If the specified file does
    not exist, this setting is ignored.-->
    <add key="AlternateConfig" value="C:\Temp\crmsample.exe.config"/>
  </appSettings>

 </configuration>

The fields have been filled with placeholder information for obvious reasons :)

Another issue might be that my line manager authorised the app using Azure AD since he has full control and I am trying to authorise the app using my credentials, but I am almost 100% certain this is NOT the case as changing the username and password fields made no difference to what error I was getting.

Could you please let me know what I am missing? I suspect it's something simple, but I have been reading through MSDN docs for the last 2 days and can't seem to sort my problem out.

*This post is locked for comments

I have the same question (0)

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

Responsible AI policies

As AI tools become more common, we’re introducing a Responsible AI Use…

Pallavi Phade – Community Spotlight

We are honored to recognize Pallavi Phade as our Community Spotlight honoree for…

Leaderboard > 🔒一 Microsoft Dynamics CRM (Archived)

#1
Community Member Profile Picture

Community Member 2

#1
UllrSki Profile Picture

UllrSki 2

#3
SC-08081331-0 Profile Picture

SC-08081331-0 1

Last 30 days Overall leaderboard

Featured topics

Product updates

Dynamics 365 release plans