如何使用用户名和密码连接到mscrm?

时间:2012-09-08 13:11:38

标签: authentication dynamics-crm credentials

如何替换和扩展此代码以在身份验证凭据中使用密码和用户名。我试图通过分析mscrm sdk中的示例来解决这个问题,但没有运气,因为我不是c#程序员。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.ServiceModel.Description;
using Microsoft.Xrm.Sdk.Client;
using System.Net;
using Microsoft.Xrm.Sdk;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void id_Click(object sender, EventArgs e)
    {

        AuthenticationCredentials authCredentials = new AuthenticationCredentials();

        //Authenticate using credentials of the logged in user;       
        ClientCredentials Credentials = new ClientCredentials();


        Uri OrganizationUri = new Uri("http://Crm/Contoso/XRMServices/2011/Organization.svc");
        Uri HomeRealmUri = null;

        //OrganizationServiceProxy serviceProxy;       
        using (OrganizationServiceProxy serviceProxy = new OrganizationServiceProxy(OrganizationUri, HomeRealmUri, Credentials, null))
        {
            IOrganizationService service = (IOrganizationService)serviceProxy;

            //Instantiate the contact object and populate the attributes.
            Entity contact = new Entity("contact");
            contact["firstname"] = txtFirstName.Text.ToString();
            contact["lastname"] = txtLastName.Text.ToString();
            Guid newContactId = service.Create(contact);
        }
    }
}

谢谢!

2 个答案:

答案 0 :(得分:2)

我将假设您在此处使用Active Directory身份验证。 MSDN上有一个相当长的啰嗦示例,它展示了如何为所有身份验证方法创建连接。

我相信你只需要改变:

ClientCredentials Credentials = new ClientCredentials();

要:

ClientCredentials Credentials = new ClientCredentials();
Credentials.UserName.UserName = "domain\username";
Credentials.UserName.Password = "password";

答案 1 :(得分:0)

如果可能,我建议使用默认凭据,如果不可能,我们会使用以下内容:

ClientCredentials creds = new ClientCredentials();
creds.Windows.ClientCredential = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["username"], ConfigurationManager.AppSettings["password"], ConfigurationManager.AppSettings["domain"]);

这种方法的明显缺点是密码是明文的,但好处是你不需要重新编译来更改密码或用户。