Connect to Dynamics CRM WebApi from Console Application (Without Authentication popup)

Hi Friends, This is the quick post as an extension to my previous post on How to connect to Dynamics CRM Webapi from Console application where I have discussed how to do the app registration in the Azure, Getting the client Id, Generating token and then Connecting to the WebAPI using the generated token.

If you checked it, you can see that to generate token system will first prompt for the Credentials of the user. This may not be the desired case in some situations (for ex, you might want always use some admin credentials to connect to the service irrespective of the user who logged in). In such scenarios we would always love to hard code to some fixed credentials. We will see how do we use the AcquireTokenAsync overriden method which will accept UserCredential object.

To use this method, you are supposed to follow all the steps as mentioned in the previous post except while calling the AcquireTokenAsync in GetToken method, replace it with following 2 lines.

// UserCrendetial object will only accept User Id
//          starting from the latest version of .NET
// Thats the reason why we are using UserPasswordCredential
//         object which is actually inherited by UserCredential.
UserCredential credentials =
new UserPasswordCredential(userId, password);

//Genertae the AuthToken by using Credentials object.
authToken = await authContext.AcquireTokenAsync
(resourceUrl, clientId, credentials);

You can see we are using UserPasswordCredential object which holds the required user id & password (ofcourse, these should be valid CRM user credentials :)) and using the same to generate AuthToken.

So overall the GetToken method looks like


internal static async void GetToken(string userId, string password)
{
// Get the Resource Url & Authority Url using the Api method. This is the best way to get authority URL
// for any Azure service api.
AuthenticationParameters ap = AuthenticationParameters.CreateFromResourceUrlAsync(new Uri(apiUrl)).Result;

string resourceUrl = ap.Resource;
string authorityUrl = ap.Authority;

//Generate the Authority context .. For the sake of simplicity for the post, I haven't splitted these
// in to multiple methods. Ideally, you would want to use some sort of design pattern to generate the context and store
// till the end of the program.
authContext = new AuthenticationContext(authorityUrl, false);

// UserCrendetial object will only accept User Id
//          starting from the latest version of .NET
// Thats the reason why we are using UserPasswordCredential
//         object which is actually inherited by UserCredential.
UserCredential credentials =
new UserPasswordCredential(userId, password);

//Genertae the AuthToken by using Credentials object.
authToken = await authContext.AcquireTokenAsync
(resourceUrl, clientId, credentials);

WriteLine("Got the authentication token, Getting data from Webapi !!");

GetData(authToken.AccessToken);
}

Note that, the rest of the program which we saw in the previous works as is.

Now, as usual – some of the key points to remember

  • I have read in many posts that it is not a suggestible approach to hard code the credentials like this in terms of Security.
  • For the sake of simplicity and quick blogging, I haven’t followed any design patterns while writing the code. It is expected that you will be using it as a base to understand the concept and implement in your own way.
  • There is a way to generate Client Secret and client id as well in Azure, but it is not working properly as I expected and my initial investigation says that it is intended to use only for Native applications (like WebApp/api). Not 100% sure on this, would be very much happy to learn on that front if you have any info.

I hope this post will help you in connecting webapi with out prompting for user id & password. Please let me & others know your opinions and how you are planning to use it in your implementations.

Happy coding !!

 

4 thoughts on “Connect to Dynamics CRM WebApi from Console Application (Without Authentication popup)

  1. Hi There, this works well for a console application, where you can silently sign in, as the login screen flashes up for a moment and this is allowed for a console application.
    We have a situation where we have written a custom Web API service (hosted in IIS) which wraps the CRM Web API service and are struggling to get the silent sign in working when our service is invoked as a Web API application doesn’t allow for any pop-ups, even briefly. Any suggestions would be appreciated.
    Thx

    Like

    1. ansrikanth

      Hi, Just because you are creating a web api, it is not mandatory for you to use crm webapi. Instead i would encourage you to use crm service client. Is there any specific need to use crm webapi?

      Like

  2. Pingback: 控制台程序(C#)不弹出认证窗口连接到Dynamics CRM Online的Web API – 创享视界

Leave a comment