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:

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"); } }