Click here to Skip to main content
15,881,787 members
Articles / Web Development / ASP.NET
Tip/Trick

Sharepoint Forms Based Authentication - FBA - Configurations, and Snippets

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
30 Mar 2015CPOL3 min read 12.7K   2  
A detailed walk-through for configuring Forms Based Authentication FBA for Sharepoint, side by side with claims based authentication

Introduction

This tip is about creating and configuring Sharepoint FBA from scratch, but if you want a plug and play solution, you can use Sharepoint FBA Pack. The reason of writing this tip is allowing developers to have more control over the FBA.

We will discuss the following in details:

  1. Making Membership DB
  2. Configuring Web.config files
  3. Utilizing and Reusing Sharepoint login page while customizing it
  4. Code snippets for registration, password reset, etc.

Background

Of course, you must be familiar with Sharepoint, and are able to develop custom webparts. And any suggestions, edits are very welcome.

Let's Start

The first step is to configure Membership DB which is very easy using the following utility.

  • Navigate to c:\windows\Microsoft.NET\Framework64\v4.0.30319\
  • Run “aspnet_regsql.exe

Now you have a functional but empty membership database.

The next step is to decide your FBA Membership, Roles, and Connectionstring Providers Names.
Let them be:

  • ProjectX_FBA_Membership
  • ProjectX_FBA_Roles
  • ProjectX_DB

Now, you will need to modify 3 Web.config files:

  • STS web.config
  • Central Admin web.config
  • Your Application web.config

STS web.config can be found by opening IIS, then expand "SharePoint Web Services", Select "SecurityTokenServiceApplication", then explore it.
Most probably, you will NOT find <System.Web> and <Connectionstrings> sections if this is the first time to configure FBA on the server, so you have to add it, with membership, and roles providers inside.

XML
<connectionStrings>
    <add connectionString="Server={ServerURL};Database={DBName};User ID={DBUser};
	Password={DBUserPassword};" name="ProjectX_DB" />
</connectionStrings>
<system.web>
    <membership>
        <providers>
            <add name="ProjectX_FBA_Membership
        type="System.Web.Security.SqlMembershipProvider, System.Web, Version=4.0.0.0, 
		Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
        connectionStringName="ProjectX_DB"
        enablePasswordRetrieval="false"
        enablePasswordReset="true"
        requiresQuestionAndAnswer="false"
        applicationName="/"
        requiresUniqueEmail="false"
        passwordFormat="Hashed"
        maxInvalidPasswordAttempts="5"
        minRequiredPasswordLength="7"
        minRequiredNonalphanumericCharacters="1"
        passwordAttemptWindow="10"
        passwordStrengthRegularExpression="" />
        </providers>
    </membership>
    <roleManager>
        <providers>
            <add name="ProjectX_FBA_Roles" 
            connectionStringName="ProjectX_DB" applicationName="/"
        type="System.Web.Security.SqlRoleProvider, System.Web, Version=4.0.0.0, 
		Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
        </providers>
    </roleManager>
</system.web>

Feel free to replace all tokens inside the {} and play with the configurations as you need.

Repeat the same with Central Admin, and your application web.config files, while leaving default providers as is (Usually "i" and "c"). Also, add your provider line after the default one.

Bonus Tip

You can use the following web.config snippet in STS web.config, to get more detailed errors in the Windows event viewer.

Before the end of:

XML
<behavior name="SecurityTokenServiceBehavior" >

Add:

XML
<serviceDebug includeExceptionDetailInFaults="True" httpHelpPageEnabled="True"/>

Reusing Sharepoint Login Page, and Customizing It

In the following, we will make a normal Sharepoint page, and assign it a custom page layout, which uses our custom class as code-behind.

Firstly, make a custom partial login class that inherits from "FormsSignInPage". Don't forget to reference Assembly "Microsoft.SharePoint.IdentityModel.dll".

Then, you can override "OnPreInit" to use specific master page, and override "OnLoad" to inject any extra controls like captcha, etc., and "IsLoginControlInValidState", etc.

Make sure to register your custom code class as safe control, and deploy it to GAC, in your Sharepoint project package (Advanced tab).

In the pagelayout, just reference your custom code as the following:

ASP.NET
<%@ Assembly Name="AuthenticationProj, Version=1.0.0.0, Culture=neutral, 
	PublicKeyToken=e7a0150b00ecca7a" %>

<%@ Page Language="C#" Debug="true" Inherits="AuthenticationProj.CustomLoginClass" 
	meta:progid="SharePoint.WebPartPage.Document" %>

Then use normal asp.net login control and format it as you want
<asp:login />

Of course, don't forget to configure your application authentication provider in central administration with the providers' names used in the configurations above.

Code Snippets

C#
//Using Assembly System.Web.ApplicationServices.dll

//To Register new users
MembershipCreateStatus creationStatus = new MembershipCreateStatus();
var membershipUser = Membership.CreateUser
	(txtUserName.Text, txtPassword.Text, txtEmail.Text, null, null, true, out creationStatus);

//To make sure that the user is authenticated, otherwise, redirect him to login page
SPUtility.EnsureAuthentication();

//Read Provider name by code
SPIisSettings iisSettings = 
	SPContext.Current.Site.WebApplication.IisSettings[SPUrlZone.Internet];
SPFormsAuthenticationProvider formsClaimsAuthenticationProvider = 
				iisSettings.FormsClaimsAuthenticationProvider;
formsClaimsAuthenticationProvider.MembershipProvider;

//To change password, you will need to reset it, first, then use it as the current password
private MembershipProvider formsMembershipProvider = null;
SPIisSettings iisSettings = 
	SPContext.Current.Site.WebApplication.IisSettings[SPUrlZone.Internet];
SPFormsAuthenticationProvider formsClaimsAuthenticationProvider = 
				iisSettings.FormsClaimsAuthenticationProvider;
formsMembershipProvider = 
		Membership.Providers[formsClaimsAuthenticationProvider.MembershipProvider];
formsMembershipProvider.ChangePassword
	(username, formsMembershipProvider.ResetPassword(username, null), NewPassword);

Important Note: The code isn't copy paste ready, so read and understand before copying it.

Points of Interest

You can write code behind for normal Sharepoint pages, using custom layout that refers to custom code, without the need to use farm level application pages.

You can reuse Sharepoint login page, and let it do all the work without reinventing the wheel while having the ability to modify it.

History

  • 30th March, 2015: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Egypt Egypt
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --