locked
HTTP status 401: Unauthorised RRS feed

  • Question

  • Hello there,

    i have the following code:

    using

    System;

    using

    System.Collections.Generic;

    using

    System.Text;

    using

    System.Net;

    using

    CRMUtils.localhost;

    namespace

    CRMUtils

    {

     

    public class CRMUtils

    {

     

     

     

    public static void UpdateBouncedLeadEmail()

    {

     

    CrmService crmservice = CRMUtils.GetCrmService("http://localhost:5555", "LitwareInc.com");

     

    QueryExpression query = new QueryExpression();

    query.EntityName =

    EntityName.lead.ToString();

    query.ColumnSet =

    new AllColumns();

     

    RetrieveMultipleRequest retrieve = new RetrieveMultipleRequest();

    retrieve.Query = query;

     

    RetrieveMultipleResponse retrieved2 = (RetrieveMultipleResponse)crmservice.Execute(retrieve);

     

    foreach (BusinessEntity be in retrieved2.BusinessEntityCollection.BusinessEntities)

    {

     

    lead objLead = (lead)be;

     

    if (objLead.emailaddress1.Equals("x@abc.com"))

    objLead.new_bouncedemailind.Value = 1;

    }

    }

     

    public static CrmService GetCrmService(string crmServerUrl, string organizationName)

    {

     

    // Get the CRM Users appointments

     

    // Setup the Authentication Token

     

    CrmAuthenticationToken token = new CrmAuthenticationToken();

    token.OrganizationName = organizationName;

     

    CrmService service = new CrmService();

     

    if (crmServerUrl != null &&

    crmServerUrl.Length > 0)

    {

     

    UriBuilder builder = new UriBuilder(crmServerUrl);

    builder.Path =

    "//MSCRMServices//2007//CrmService.asmx";

    service.Url = builder.Uri.ToString();

    }

     

     

    CredentialCache credential = new System.Net.CredentialCache();

     

    NetworkCredential netCred = new NetworkCredential("administrator","pass@word1","litwareinc.com");

    credential.Add(

    new Uri("http://localhost:5555"),"NTLM", netCred);

    service.Credentials = credential;

     

    return service;

    }

     

    }

    }



    When I tried to use a Console application that calls just UpdateBouncedLeadEmail above, I get a "...401: Unauthorised" error.  Please help!

    Regards,
    JPL1538

    Tuesday, February 23, 2010 9:36 PM

Answers

  • OK, if it's AD, then try using the server name instead of localhost.

    Also you're not specifying an organisation to connect to.

    token.OrganizationName = myOrganizationName;
    
    Here's a full sample from the SDK

    [C#]
    // STEP 1: Instantiate and configure the CrmDiscoveryService Web service.
    CrmDiscoveryService discoveryService = new CrmDiscoveryService();
    discoveryService.UseDefaultCredentials = true;
    discoveryService.Url = "http://localhost:5555/MSCRMServices/2007/AD/CrmDiscoveryService.asmx";
    
    // STEP 2: Retrieve the desired organization name and endpoint URL from the
    // CrmDiscoveryService Web service.
    RetrieveOrganizationsRequest orgRequest = new RetrieveOrganizationsRequest();
    RetrieveOrganizationsResponse orgResponse =
        (RetrieveOrganizationsResponse)discoveryService.Execute(orgRequest);
    
    OrganizationDetail orgInfo = null;
    foreach (OrganizationDetail orgDetail in orgResponse.OrganizationDetails)
    {
        if (orgDetail.OrganizationName.Equals("AdventureWorksCycle"))
        {
            orgInfo = orgDetail;
            break;
        }
    }
    
    if (orgInfo == null)
        throw new Exception("The organization name is invalid.");
    
    // STEP 3: Create and configure an instance of the CrmService Web service.
    CrmAuthenticationToken token = new CrmAuthenticationToken();
    token.AuthenticationType = 0; // See Microsoft.Crm.Sdk.AuthenticationType
    token.OrganizationName = orgInfo.OrganizationName;
    
    CrmService crmService = new CrmService();
    crmService.Url = orgInfo.CrmServiceUrl;
    crmService.CrmAuthenticationTokenValue = token;
    crmService.Credentials = System.Net.CredentialCache.DefaultCredentials;
    
    // STEP 4: Invoke a CrmService Web service method.
    WhoAmIRequest whoRequest = new WhoAmIRequest();
    WhoAmIResponse whoResponse = (WhoAmIResponse)crmService.Execute(whoRequest);
    


    @_Simon_Jackson http://www.simonjackson.info/ MBCS MCBMSS MCBMSP MCSD MCDBA MCAD MCSA
    Wednesday, February 24, 2010 6:00 AM

All replies

  • you've not set the token AuthenticationType ...

    token.AuthenticationType = 0; //AD - there are other values for IFD and Crm 


    @_Simon_Jackson http://www.simonjackson.info/ MBCS MCBMSS MCBMSP MCSD MCDBA MCAD MCSA
    Tuesday, February 23, 2010 10:14 PM
  • Hi there,

    I have made the changes as suggested:

     

    public static CrmService GetCrmService(string crmServerUrl, string organizationName)

    {

     

    // Get the CRM Users appointments

     

    // Setup the Authentication Token

     

    CrmAuthenticationToken token = new CrmAuthenticationToken();

    token.OrganizationName = organizationName;

    token.AuthenticationType = 2;

     

    CrmService service = new CrmService();

     

    if (crmServerUrl != null &&

    crmServerUrl.Length > 0)

    {

     

    UriBuilder builder = new UriBuilder(crmServerUrl);

    builder.Path =

    "//MSCRMServices//2007//CrmService.asmx";

    service.Url = builder.Uri.ToString();

     

    }

     

     

    CredentialCache credential = new System.Net.CredentialCache();

     

    NetworkCredential netCred = new NetworkCredential("administrator","pass@word1","litwareinc.com");

     

    credential.Add(

    new Uri("http://localhost:5555"),"NTLM", netCred);

     

    service.Credentials = credential;

    service.CrmAuthenticationTokenValue = token;

     

    return service;

    }

    but still get the same error.

    Is there anything else outside of code, I need to take care of as well?

    Thanks,
    JPL1538

    Tuesday, February 23, 2010 10:20 PM
  • Oh, ok it's an IFD deployment.

    Here's the example from the SDK notice the use of the RetrieveCrmTicketRequest
    using System;
    using System.Xml;
    using System.Text;
    using System.Web.Services.Protocols;
    
    // Microsoft Dynamics CRM namespaces.
    // Note that the Visual Studio project name is IFD_Authentication.
    using IFD_Authentication.CrmSdk;
    using IFD_Authentication.CrmSdk.Discovery;
    
    public class IFDConnection
    {
        // A CrmService reference.
        public readonly CrmService CrmService = null;
    
        // URL of the Web application.
        public readonly string WebApplicationUrl = String.Empty;
    
        // GUID of the user's organization.
        public readonly Guid OrganizationId = Guid.Empty; 
    
        /// <summary>
        /// Authenticate the user using IFD (Internet Facing Deployment). The class
        /// constructor sets the values of the public variables (CrmService, etc).
        /// </summary>
        /// <param name="organization">Name of the user's organization.</param>
        /// <param name="server">Microsoft Dynamics CRM server URL.
        /// For example: https://myserver.</param>
        /// <param name="domain">Name of the domain hosting the user's system
        /// account.</param>
        /// <param name="username">User's system account name.</param>
        /// <param name="password">User's account password.</param>
        public IFDConnection(string organization, string server, string domain,
                             string username, string password)
        {
            //Remove any trailing forward slash from the end of the server URL.
            server = server.TrimEnd(new char[] { '/' });
    
            // Initialize an instance of the CrmDiscoveryService Web service proxy.
            CrmDiscoveryService disco = new CrmDiscoveryService();
            disco.Url = server + "/MSCRMServices/2007/SPLA/CrmDiscoveryService.asmx";
    
            //Retrieve a list of available organizations.
            RetrieveOrganizationsRequest orgRequest = 
                new RetrieveOrganizationsRequest();
            orgRequest.UserId = domain + "\\" + username;
            orgRequest.Password = password;
            RetrieveOrganizationsResponse orgResponse =
                (RetrieveOrganizationsResponse)disco.Execute(orgRequest);
    
            //Find the desired organization.
            foreach (OrganizationDetail orgdetail in orgResponse.OrganizationDetails)
            {
                if (orgdetail.OrganizationName == organization)
                {
                    //Retrieve the ticket.
                    RetrieveCrmTicketRequest ticketRequest = 
                        new RetrieveCrmTicketRequest();
                    ticketRequest.OrganizationName = organization;
                    ticketRequest.UserId = domain + "\\" + username;
                    ticketRequest.Password = password;
                    RetrieveCrmTicketResponse ticketResponse = 
                        (RetrieveCrmTicketResponse)disco.Execute(ticketRequest);
    
                    //Create the CrmService Web service proxy.
                    CrmAuthenticationToken sdktoken = new CrmAuthenticationToken();
                    sdktoken.AuthenticationType = 2;
                    sdktoken.OrganizationName = organization;
                    sdktoken.CrmTicket = ticketResponse.CrmTicket;
    
                    CrmService = new CrmService();
                    CrmService.CrmAuthenticationTokenValue = sdktoken;
                    CrmService.Url = orgdetail.CrmServiceUrl;
    
                    WebApplicationUrl = orgdetail.WebApplicationUrl;
                    OrganizationId = orgdetail.OrganizationId;
    
                    break;
                }
            }
        }
    }


    @_Simon_Jackson http://www.simonjackson.info/ MBCS MCBMSS MCBMSP MCSD MCDBA MCAD MCSA
    Tuesday, February 23, 2010 10:42 PM
  • Hi there,

    Sorry, I did set the AuthenticationType to 0, it should be AD, but that didn't work and I tried the other values as well and left the code that way when I pasted it here.

    The AD is located on the same server where the CRM is.  So I am not sure what else I am missing.

    Even setting the AutheticationType to 0, I get the same 401 error.

    Please help!

    Regards,
    JPL1538
    Tuesday, February 23, 2010 11:01 PM
  • Is "administrator" a user in CRM? Are you able to access the web application using this account?

    Wednesday, February 24, 2010 4:50 AM
  • OK, if it's AD, then try using the server name instead of localhost.

    Also you're not specifying an organisation to connect to.

    token.OrganizationName = myOrganizationName;
    
    Here's a full sample from the SDK

    [C#]
    // STEP 1: Instantiate and configure the CrmDiscoveryService Web service.
    CrmDiscoveryService discoveryService = new CrmDiscoveryService();
    discoveryService.UseDefaultCredentials = true;
    discoveryService.Url = "http://localhost:5555/MSCRMServices/2007/AD/CrmDiscoveryService.asmx";
    
    // STEP 2: Retrieve the desired organization name and endpoint URL from the
    // CrmDiscoveryService Web service.
    RetrieveOrganizationsRequest orgRequest = new RetrieveOrganizationsRequest();
    RetrieveOrganizationsResponse orgResponse =
        (RetrieveOrganizationsResponse)discoveryService.Execute(orgRequest);
    
    OrganizationDetail orgInfo = null;
    foreach (OrganizationDetail orgDetail in orgResponse.OrganizationDetails)
    {
        if (orgDetail.OrganizationName.Equals("AdventureWorksCycle"))
        {
            orgInfo = orgDetail;
            break;
        }
    }
    
    if (orgInfo == null)
        throw new Exception("The organization name is invalid.");
    
    // STEP 3: Create and configure an instance of the CrmService Web service.
    CrmAuthenticationToken token = new CrmAuthenticationToken();
    token.AuthenticationType = 0; // See Microsoft.Crm.Sdk.AuthenticationType
    token.OrganizationName = orgInfo.OrganizationName;
    
    CrmService crmService = new CrmService();
    crmService.Url = orgInfo.CrmServiceUrl;
    crmService.CrmAuthenticationTokenValue = token;
    crmService.Credentials = System.Net.CredentialCache.DefaultCredentials;
    
    // STEP 4: Invoke a CrmService Web service method.
    WhoAmIRequest whoRequest = new WhoAmIRequest();
    WhoAmIResponse whoResponse = (WhoAmIResponse)crmService.Execute(whoRequest);
    


    @_Simon_Jackson http://www.simonjackson.info/ MBCS MCBMSS MCBMSP MCSD MCDBA MCAD MCSA
    Wednesday, February 24, 2010 6:00 AM
  • Hi

    I hope you are using CRM VPC.

    Leave the domain name and try

    NetworkCredential netCred = new NetworkCredential("administrator","password");

    if still problem persist it may be dur to Kerberos. Try this

    CredentialCache credential = new System.Net.CredentialCache();
    NetworkCredential netCred = new NetworkCredential("administrator", "pass@word1", "litwareinc");
    credential.Add(new Uri("http://localhost:5555"), "NTLM", netCred);
    crmDeployService.Credentials = credential;

    Sample code to ckeck:

    // Set up the CRM Service.
    CrmAuthenticationToken token = new CrmAuthenticationToken();
    token.AuthenticationType = 0;
    token.OrganizationName = "AdventureWorksCycle";

    CrmService service = new CrmService();
    service.Url = "http://<servername>:<port>/mscrmservices/2007/crmservice.asmx";
    service.CrmAuthenticationTokenValue = token;
    service.Credentials = new NetworkCredential("administrator","password");
    //service.Credentials = System.Net.CredentialCache.DefaultCredentials;

    // Create an account entity and assign data to some attributes.
    account newAccount = new account();
    newAccount.name = "Greg Bike Store";
    newAccount.accountnumber = "123456";
    newAccount.address1_postalcode = "98052";
    newAccount.address1_city = "Redmond";

    // Call the Create method to create an account.
    Guid accountId = service.Create(newAccount);

    Regards
    Vinoth

    Wednesday, February 24, 2010 6:15 AM