Tuesday, July 2, 2013

SharePoint : Forms authentication using Active Directory

This post explains how to authenticate forms credentials against active directory in SharePoint.

The following code goes into login button click event on signin page where users are auto redirected.
HttpRequest request = HttpContext.Current.Request;

//Get the zone which is setup for forms authentication
SPIisSettings iisSettings = SPContext.Current.Site.WebApplication.IisSettings[SPUrlZone.Extranet];

//Retrive forms authentication provider 
SPFormsAuthenticationProvider formsClaimsAuthenticationProvider = iisSettings.FormsClaimsAuthenticationProvider;

//Create forms token using forms authentication provider settings and login details
SecurityToken token = SPSecurityContext.SecurityTokenForFormsAuthentication(new Uri(SPContext.Current.Web.Url), 
    formsClaimsAuthenticationProvider.MembershipProvider,  //Set while creating/extending web application
    formsClaimsAuthenticationProvider.RoleProvider,        //Set while creating/extending web application
    signInControl.UserName,                                //Received from login page
    signInControl.Password,                                //Received from login page

if (null != token)
    //Create forms session using the token
    //Please note that the following function is copied from other blog

    //Redirect to required home page

private void EstablishSessionWithToken(SecurityToken securityToken)
    if (securityToken == null)
        throw new ArgumentNullException("securityToken");
    SPFederationAuthenticationModule fam = FederatedAuthentication.WSFederationAuthenticationModule as SPFederationAuthenticationModule;
    if (fam == null)
        throw new InvalidOperationException();
    SPSecurity.RunWithElevatedPrivileges(() => fam.SetPrincipalAndWriteSessionToken(securityToken));

Create the following XML entries in web.config file


Add the following membership provider details into / element in web.config

Please note that the membership provider name we specify above should match the membership provider name in authentication details which is set while creating the web application.
So the code in login page, connection string and provider details in web.config should all work together and get us authentication using forms against active directory.

Please also note that some code is taken from other blogs.

No comments:

Post a Comment