Search code examples
web-servicescrmdynamics-crm-4service-tier

Authenticate with MS Crm Web Service


I'm looking for a way to authenticate a user (given a username and password) via the Microsoft CRM 4.0 Web Services API. Ideally, I'd like to filter down a list of projects based on which ones the logged in user has access to. i may be able to figure out the second part but I can't find a way to authenticate the user. The way all of the cals are currently made in the web service is via:

MyWebServices.CrmService svc = new MyWebServices.CrmService();
MyWebServices.CrmAuthenticationToken token = new MyWebServices.CrmAuthenticationToken();
token.OrganizationName = "MyCRM";
token.AuthenticationType = 0;
svc.CrmAuthenticationTokenValue = token;
svc.PreAuthenticate = true;
svc.Credentials = System.Net.CredentialCache.DefaultCredentials;
svc.Credentials = new NetworkCredential("hj", "mypass", "mydomain");

Then calls can be made via the service. I guess I could potentially try to authenticate to CRM via the user's username/password but it feels wrong somehow.


Solution

  • If you are in an on-premise environment, you should be able to use the following code to get a valid CRM service that can be used to retrieve your projects.

    public static Microsoft.Crm.SdkTypeProxy.CrmService GetCrmService(string crmServerUrl, string organizationName, System.Net.NetworkCredential networkCredential)
    {
        // Setup the Authentication Token
        CrmAuthenticationToken crmAuthenticationToken = new CrmAuthenticationToken
                                               {
                                                   OrganizationName = organizationName,
                                                   AuthenticationType = 0
                                               };
    
        var crmServiceUriBuilder = new UriBuilder(crmServerUrl) { Path = "//MSCRMServices//2007//CrmService.asmx" };
    
        // Instantiate a CrmService
        var crmService = new Microsoft.Crm.SdkTypeProxy.CrmService
        {
            Url = crmServiceUriBuilder.ToString(),
            UseDefaultCredentials = false,
            Credentials = networkCredential,
            CrmAuthenticationTokenValue = crmAuthenticationToken
        };
    
        return crmService;
    }