Skip to main content

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :
Microsoft Dynamics CRM (Archived)

Dynamics 365 Authorization returns 401: Unauthorized

(0) ShareShare
ReportReport
Posted on by

I'm using the code below:

class Program
    {
        static void Main(string[] args)
        {
            string organizationUrl = "beehexa0.crm5.dynamics.com";
            string clientId = "965c544c-8c64-44f2-ac4f-ec51d3f09d06";
            string appKey = "...";
            string aadInstance = "login.microsoftonline.com";
            string tenantID = "ee7f9991-88f1-4e35-b2c1-18c4e51a4698";

            ClientCredential clientcred = new ClientCredential(clientId, appKey);
            AuthenticationContext authenticationContext = new AuthenticationContext(aadInstance + tenantID);
            var task = authenticationContext.AcquireTokenAsync(organizationUrl, clientcred);
            task.Wait();
            AuthenticationResult authenticationResult = task.Result;
            var requestedToken = authenticationResult.AccessToken;
            
            using (var sdkService = new OrganizationWebProxyClient(GetServiceUrl(organizationUrl), false))
            {
                sdkService.HeaderToken = requestedToken;

                OrganizationRequest request = new OrganizationRequest()
                {
                    RequestName = "WhoAmI"
                };
                try
                {
                    WhoAmIResponse response = sdkService.Execute(request) as WhoAmIResponse;
                    Console.WriteLine(response.UserId);
                } catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                    Console.WriteLine(ex.InnerException.ToString());
                }

                Console.ReadKey();
            }
        }

        static private Uri GetServiceUrl(string organizationUrl)
        {
            return new Uri(organizationUrl + @"/xrmservices/2011/organization.svc/web?SdkClientVersion=8.2");
        }
        
    }


And got Exception as below:

System.ServiceModel.Security.MessageSecurityException: The HTTP request is unauthorized with client authentication scheme 'Anonymous'. The authentication header received from the server was 'Bearer authorization_uri=login.windows.net/.../authorize, resource_id=beehexa0.crm5.dynamics.com'. ---> System.Net.WebException: The remote server returned an error: (401) Unauthorized.
   at System.Net.HttpWebRequest.GetResponse()
   at System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
   --- End of inner exception stack trace ---

Server stack trace:
   at System.ServiceModel.Channels.HttpChannelUtilities.ValidateAuthentication(HttpWebRequest request, HttpWebResponse response, WebException responseException, HttpChannelFactory`1 factory)
   at System.ServiceModel.Channels.HttpChannelUtilities.ValidateRequestReplyResponse(HttpWebRequest request, HttpWebResponse response, HttpChannelFactory`1 factory, WebException responseException, ChannelBinding channelBinding)
   at System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
   at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout)
   at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout)
   at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
   at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
   at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)

Exception rethrown at [0]:
   at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
   at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
   at Microsoft.Xrm.Sdk.IOrganizationService.Execute(OrganizationRequest request)
   at Microsoft.Xrm.Sdk.WebServiceClient.OrganizationWebProxyClient.<>c__DisplayClass40_0.<ExecuteCore>b__0()
   at Microsoft.Xrm.Sdk.WebServiceClient.WebProxyClient`1.ExecuteAction[TResult](Func`1 action)
   at Microsoft.Xrm.Sdk.WebServiceClient.OrganizationWebProxyClient.ExecuteCore(OrganizationRequest request)
   at Microsoft.Xrm.Sdk.WebServiceClient.OrganizationWebProxyClient.Execute(OrganizationRequest request)
   at Microsoft.Dynamics.Program.Main(String[] args) in C:\Workspace\Beehexa\Microsoft.Dynamics\Microsoft.Dynamics\Program.cs:line 44


Why does the Authorization Header appears to be 'Bearer authorization_uri=login.windows.net/.../authorize, resource_id=beehexa0.crm5.dynamics.com' instead of some "Bearer <valid token>"? I debugged and looks like it can get the access_token successfully:

61764.Capture.PNG

class Program    {        static void Main(string[] args)        {            string organizationUrl = "beehexa0.crm5.dynamics.com";            string clientId = "965c544c-8c64-44f2-ac4f-ec51d3f09d06";            string appKey = "KGTv1h70hHC+ohC1lAPnuq4oN1Rfoy5yxt0qdoMfm50=";            string aadInstance = "login.microsoftonline.com";            string tenantID = "ee7f9991-88f1-4e35-b2c1-18c4e51a4698";
            ClientCredential clientcred = new ClientCredential(clientId, appKey);            AuthenticationContext authenticationContext = new AuthenticationContext(aadInstance + tenantID);            var task = authenticationContext.AcquireTokenAsync(organizationUrl, clientcred);            task.Wait();            AuthenticationResult authenticationResult = task.Result;            var requestedToken = authenticationResult.AccessToken;                        using (var sdkService = new OrganizationWebProxyClient(GetServiceUrl(organizationUrl), false))            {                sdkService.HeaderToken = requestedToken;
                OrganizationRequest request = new OrganizationRequest()                {                    RequestName = "WhoAmI"                };                try                {                    WhoAmIResponse response = sdkService.Execute(request) as WhoAmIResponse;                    Console.WriteLine(response.UserId);                } catch (Exception ex)                {                    Console.WriteLine(ex.ToString());                    Console.WriteLine(ex.InnerException.ToString());                }
                Console.ReadKey();            }        }
        static private Uri GetServiceUrl(string organizationUrl)        {            return new Uri(organizationUrl + @"/xrmservices/2011/organization.svc/web?SdkClientVersion=8.2");        }            }

*This post is locked for comments

  • Community Member Profile Picture
    on at
    RE: Dynamics 365 Authorization returns 401: Unauthorized

    Looks like for querying data from CRM Online API, we need to use Azure Portal to create a Native App instead of WebAPI app and use UserPasswordCredentials instead of ClientCredentials

  • Verified answer
    Abdul Wahab Profile Picture
    12,085 Moderator on at
    RE: Dynamics 365 Authorization returns 401: Unauthorized

    Hi LeHuu,

    What do you want? I think you want to connect your crm with your console app. If yes than use below Blog:

    arunpotti.wordpress.com/.../connect-to-crm-online-or-on-premise-using-c

    If you have any queries do let me know.

    Thanks

    Regards,

    AW

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

🌸 Community Spring Festival 2025 Challenge Winners! 🌸

Congratulations to all our community participants!

Adis Hodzic – Community Spotlight

We are honored to recognize Adis Hodzic as our May 2025 Community…

Kudos to the April Top 10 Community Stars!

Thanks for all your good work in the Community!

Leaderboard > Microsoft Dynamics CRM (Archived)

#1
Mohamed Amine Mahmoudi Profile Picture

Mohamed Amine Mahmoudi 83 Super User 2025 Season 1

#2
Community Member Profile Picture

Community Member 52

#3
Victor Onyebuchi Profile Picture

Victor Onyebuchi 6

Overall leaderboard

Featured topics

Product updates

Dynamics 365 release plans