Friday, April 16, 2021

Create Custom Login Page Mixed authentication SharePoint 2013

 

In series of my SP2013 blogs my this blog describes how to “Create Custom Login Page Mixed authentication in SharePoint 2013“.

It is bit similar to SP2010 with a small change of the master page it inherits and sharepoint assembly version. So below is my code to achieve login functionality for “Windows Authentication” and “Forms Authentication“.

ASPX Page(Application Page):

Note: 1. Some things you must replace those are highlighted below.

2. Master page used for mixed mode login page is errorv15.master

3. I override click event of login button that default use CommandName=”Login”

4. Also you can use either  <%–<a href=”/_windows/default.aspx?ReturnUrlor  <asp:LinkButton ID=”lbInternalUsers” … former is easy but less in control from code, later best for controlling events.

<%@ Assembly Name="Microsoft.SharePoint.IdentityModel, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Assembly Name="$SharePoint.Project.AssemblyFullName$" %>
 
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="YourPageName.aspx.cs" Inherits="YourNameSpace.YourClassName" MasterPageFile="~/_layouts/15/errorv15.master" %>
 
<%@ Import Namespace="Microsoft.SharePoint.WebControls" %>
<%@ Register TagPrefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Import Namespace="Microsoft.SharePoint" %>
<%@ Assembly Name="Microsoft.Web.CommandUI, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="asp" Namespace="System.Web.UI" Assembly="System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" %>
 
<asp:Content ID="PageTitle" ContentPlaceHolderID="PlaceHolderPageTitle" runat="server">
    <SharePoint:EncodedLiteral runat="server" EncodeMethod="HtmlEncode" ID="ClaimsFormsPageTitle" />
</asp:Content>
 
<asp:Content ID="Main" ContentPlaceHolderID="PlaceHolderMain" runat="server">
    <div id="SslWarning" style="color: red; display: none">
        <SharePoint:EncodedLiteral runat="server" EncodeMethod="HtmlEncode" ID="ClaimsFormsPageMessage" />
    </div>
    <script language="javascript">
        if (document.location.protocol != 'https:') {
            var SslWarning = document.getElementById('SslWarning');
            SslWarning.style.display = '';
        }
    </script>
    <asp:Label ID="lblError" class="ms-error" runat="server" Visible="false" />
    <asp:Login ID="signInControl" FailureText="<%$Resources:wss,login_pageFailureText%>" runat="server" Width="100%">
        <LayoutTemplate>
            <asp:Label ID="FailureText" class="ms-error" runat="server" />
            <table width="100%">
                <tr>
                    <td nowrap="nowrap">
                        <SharePoint:EncodedLiteral ID="EncodedLiteral1" runat="server" Text="<%$Resources:wss,login_pageUserName%>" EncodeMethod='HtmlEncode' /></td>
                    <td width="100%">
                        <asp:TextBox ID="UserName" autocomplete="off" runat="server" class="ms-inputuserfield" Width="99%" /></td>
                </tr>
                <tr>
                    <td nowrap="nowrap">
                        <SharePoint:EncodedLiteral ID="EncodedLiteral2" runat="server" Text="<%$Resources:wss,login_pagePassword%>" EncodeMethod='HtmlEncode' /></td>
                    <td width="100%">
                        <asp:TextBox ID="password" TextMode="Password" autocomplete="off" runat="server" class="ms-inputuserfield" Width="99%" /></td>
                </tr>
                <tr>
                    <td colspan="2" align="right">
                        <asp:Button ID="login" OnClick="login_click" Text="<%$Resources:wss,login_pagetitle%>" runat="server" /></td>
                    <!--CommandName="Login"-->
                </tr>
                <tr>
                    <td colspan="2">
                        <asp:CheckBox ID="RememberMe" Text="<%$SPHtmlEncodedResources:wss,login_pageRememberMe%>" runat="server" /></td>
                </tr>
            </table>
        </LayoutTemplate>
    </asp:Login>
    <br />
    <h2>Admin Login</h2>   
    <%--<a href="/_windows/default.aspx?ReturnUrl=<%=Request.QueryStringource"] %>">Click here to login</a>    --%>
 <asp:LinkButton ID="lbInternalUsers" Text="Click here to login" runat="server" Font-Names="Calibri" Font-Size="Small" CssClass="ms-standardheader" Font-Bold="true" ForeColor="Green" OnClick="lbInternalUsers_OnClick"></asp:LinkButton>
 
</asp:Content>

Code(cs class):
Note: 1.
In forms replace "subsiteurl" with server relative url of the subsite.
2. In forms replace "YourPage" with the page name where you want to redirect user after login.  protected void login_click(object sender, EventArgs e)         {             try             {                 //Check and validate the user is exists with the right user and password or not                                 if (SPClaimsUtility.AuthenticateFormsUser(new Uri(SPContext.Current.Web.Url), signInControl.UserName, signInControl.Password))                 {                     SPSecurity.RunWithElevatedPrivileges(delegate()                     {                         string loginName = "i:0#.f|fbamembershipprovider|" + signInControl.UserName;                         using (SPSite site = new SPSite(SPContext.Current.Site.Url))                         {                             using (SPWeb web = site.OpenWeb())                             {                                 SPUser spUser = web.AllUsers[loginName];                                 if (spUser != null)                                 {                                     bool IsUserInGroupA = false;                                     bool IsUserInGroupB = false;                                     foreach (SPGroup spGroup in spUser.Groups)                                     {                                         if (spGroup.Name == "A")                                         {                                             IsUserInGroupA = true;                                             break;                                         }                                         if (spGroup.Name == "B")                                         {                                             IsUserInGroupB = true;                                             break;                                         }                                     }                                     if (IsUserInGroupA)                                     {                                         SPUtility.Redirect(web.Webs["subsiteurl"].Url + "/Pages/YourPage.aspx", SPRedirectFlags.Trusted, this.Context);                                         //FormsAuthentication.RedirectFromLoginPage();                                     }                                     else if (IsUserInISGTFGroup)                                     {                                          //SPUtility.Redirect(web.Webs["subsiteurl"].Url + "/Pages/YourPage.aspx", SPRedirectFlags.Trusted, this.Context);                                         //FormsAuthentication.RedirectFromLoginPage();                                     }                                     else                                     {                                         SPUtility.Redirect(web.Url, SPRedirectFlags.Trusted, this.Context);                                                                             }                                 }                             }                         }                     });                 }                 else                 {                     lblError.Visible = true;                     lblError.Text = "The server could not sign you in. Make sure your user name and password are correct, and then try again.";                 }             }             catch (Exception ex)             {             }         }         

protected void lbInternalUsers_OnClick(object sender, EventArgs e)         {             try             {                 if (null != SPContext.Current && null != SPContext.Current.Site)                 {                     SPIisSettings iisSettings = SPContext.Current.Site.WebApplication.IisSettings[SPUrlZone.Default];                     if (null != iisSettings && iisSettings.UseWindowsClaimsAuthenticationProvider)                     {                         SPAuthenticationProvider provider = iisSettings.WindowsClaimsAuthenticationProvider;                         Redirect(provider);                     }                 }             }             catch (Exception ex)             {                 //lblError.Text = ex.Message;             }         }         

private void Redirect(SPAuthenticationProvider provider)         {             string comp = HttpContext.Current.Request.Url.GetComponents(UriComponents.Query, UriFormat.SafeUnescaped);             string url = provider.AuthenticationRedirectionUrl.ToString();             if (provider is SPWindowsAuthenticationProvider)             {                 comp = EnsureUrl(comp, true);             }             SPUtility.Redirect(url, SPRedirectFlags.Default, this.Context, comp);         }         

private string EnsureUrl(string url, bool urlIsQueryStringOnly)         {             if (!url.Contains("ReturnUrl="))             {                 if (urlIsQueryStringOnly)                 {                     url = url + (string.IsNullOrEmpty(url) ? "" : "&");                 }                 else                 {                     url = url + ((url.IndexOf('?') == -1) ? "?" : "&");                 }                 url = url + "ReturnUrl=";             }             return url;         }

So this is the crisp about creating full controlled login page for SP 2013 in mixed authentication mode.

This is how my login page look like.




No comments:

Post a Comment

Server Error in '/' Application when activating "Nintex Forms" web app feature.

Apparently "INSTALL-NFService" need to be run in SharePoint PowerShell to fix this problem.   When I installed Nintex Forms agai...