To create the web part, open Visual Studio and add a new web part to your project. We’ll call the web part LoginForm. In the LoginFormUserControl, you’ll want to have something like the following to accept the username and password:
<table class="tbldetails">
<tr>
<td class="tddetails">
<span class="mandatory">*</span><span class="spfields">Username:</span>
</td>
<td>
<asp:TextBox runat="server" ID="Username" CssClass="required textbox" />
</td>
</tr>
<tr>
<td>
<span class="mandatory">*</span><span class="spfields">Password:</span>
</td>
<td>
<asp:TextBox runat="server" ID="Password" TextMode="Password" CssClass="required textbox" />
</td>
</tr>
<tr>
<td colspan="2">
<asp:Button ID="Login" CssClass="btnLogin" Text="Login Now"
runat="server" onclick="Login_Click" />
</td>
</tr>
</table>
In the code behind of the user control, you’ll want to have something like this:
protected void Login_Click(object sender, EventArgs e)
{
if (Membership.ValidateUser(Username.Text, Password.Text))
{
SecurityToken tk = SPSecurityContext.SecurityTokenForFormsAuthentication(
new Uri(SPContext.Current.Web.Url), "ADProvider", null,
Username.Text, Password.Text);
if (tk != null)
{
SPFederationAuthenticationModule fam = SPFederationAuthenticationModule.Current;
fam.SetPrincipalAndWriteSessionToken(tk);
//look for the Source query string parameter and use that as the redirection
string src = page.Request.QueryString["Source"];
if (!string.IsNullOrEmpty(src))
{
Response.Redirect(src, false);
}
else
{
Response.Redirect("/", false);
}
}
}
}
The code is easy – getting it to compile is slightly more difficult. Finding the namespaces (and the dll’s that contain them) for some of these classes proved to be difficult.
- SecurityToken is in the System.Security.IdentityModel.Tokens namespace.
- SPSecurityContext is in the Microsoft.Sharepoint namespace.
- SPFederationAuthenticationModule is in the Microsoft.Sharepoint.IdentityModel namespace.
The Microsoft.IdentityModel and Microsoft.Sharepoint.IdentityModel dll’s can be found here:
- C:\Windows\assembly\GAC_MSIL\Microsoft.SharePoint.IdentityModel\14.0.0.0__71e9bce111e9429c\Microsoft.SharePoint.IdentityModel.dll
- C:\Windows\assembly\GAC_MSIL\Microsoft.IdentityModel\3.5.0.0__31bf3856ad364e35\Microsoft.IdentityModel.dll
Once you have you web part in place (and compiling), add it to a login page, deploy it to Sharepoint, and you’re done.
I looked everywhere for a solution like this. And finally :)
ReplyDeleteThis is worked!
And some information from me:
- Microsoft.IdentityModel.dll also can be found in "%ProgramFiles%Reference AssembliesMicrosoftWindows Identity Foundationv3.5"
- Your line of code which uses "Page" variable is little wrong:
This: string src = page.Request.QueryString["Source"];
Should Be As: string src = Page.Request.QueryString["Source"];
Thank you for this great post :)