Search This Blog

Thursday, October 8, 2015

Authencate username and password in SharePoint 2010 programatically


I used this method on a Windows Form Application and it works fine:

private bool loginSharePoint()
    {
        lbLoginStatus.Text = "Logging in Sharepoint server";

        bool isValid = false;

        //validating Sharepoint login
        string spUsername = tbSharePointUsername.Text;

        string spPassword = tbSharePointPassword.Text;


        pc = new PrincipalContext(ContextType.Domain, spUsername.Split('\\')[0]);

        pbLogin.PerformStep();
        // validate the credentials
        isValid = pc.ValidateCredentials(spUsername.Split('\\')[1], spPassword);
        if (isValid)
        {
            pbLogin.PerformStep();

            pbLogin.PerformStep();
            site = new SPSite(tbSharePointUrl.Text);

            pbLogin.PerformStep();
            web = site.OpenWeb();

            pbLogin.PerformStep();
            if (web.DoesUserHavePermissions(spUsername, SPBasePermissions.Open))
                isValid = true;
            else
                isValid = false;
        }


        return isValid;
    }

  string Url = txtSiteURL.Text.ToString();

                    SPSite spSite = new SPSite(Url);
                    PrincipalContext Context = new PrincipalContext(ContextType.Domain);
                    string oUser = txtDomain.Text.ToString() + "\\" + txtUsername.Text.ToString();
                    string oPassword = txtPassword.Text.ToString();
                    bool oVar;
                    using (Context)
                    {
                        oVar = Context.ValidateCredentials(oUser, oPassword);
                    }