Sharepoint 2013 - FBA和2FA以及自定义登录页面

时间:2017-05-26 10:44:58

标签: authentication sharepoint 12factor

我是Sharepoint中的一个完整的菜鸟。我2周前刚刚开始学习sharepoint,因为我的老板把我分配到了一个sharepoint项目。我必须在现有的基于声明的Intranet Web应用程序中实现2FA和FBA。我只是通过研究来完成一项简单的任务,但我还没有为我的问题找到明确的指导或答案。

以下是我的一些任务:

1)将基于表单的身份验证添加到站点并使用自定义登录页面。

2)身份验证

  • 登录后用AD检查用户的姓名和密码。
  • 如果有效,则必须向第三方提供商请求OTP代码 2FA。
  • 用户在通过后验证。

配置和自定义登录页面没有太大的麻烦,并没有花很长时间来完成它们。但是我被困在2FA部分。

1)如何自定义身份验证过程?我不记得我从哪里得到下面的代码,但我真的希望我能用它做点什么。那么,我能用它做点什么还是我走错了路?我非常感谢任何帮助,并提前感谢。

protected void btnLogin_Click(object sender, EventArgs e)
    {
        bool status = SPClaimsUtility.AuthenticateFormsUser(
            Context.Request.UrlReferrer,
            txtUsername.Value.ToString(),
            txtPassword.Value.ToString());

        if (!status) // if auth failed
        {
            lblInvalid.InnerText = "Wrong Username or Password";
            lblInvalid.Visible = true;
        }
        else //if success
        {       
    //What do I do here to change the user back to not authenticated?   

        }
    }

2 个答案:

答案 0 :(得分:0)

正确登录设置联合身份验证Cookie域后。

HttpCookie httpCookie = current.Response.Cookies["FedAuth"];
httpCookie.Domain = "." + ConfigurationManager.AppSettings["yourdomain"];

退出方法更复杂,很久以前我的解决方案基于this post

并根据sharepoint SignOut页面退出方法(抱歉变量名称,但我反编译我的旧dll)并从帖子中修复:

public static void SignOut(SPSite site, SPWeb web, IClaimsPrincipal principal)
{
    HttpContext current = HttpContext.Current;
    if (current.Session != null)
    {
        current.Session.Clear();
    }
    string value = string.Empty;
    if (current.Request.Browser["supportsEmptyStringInCookieValue"] == "false")
    {
        value = "NoCookie";
    }
    HttpCookie httpCookie = current.Request.Cookies["WSS_KeepSessionAuthenticated"];
    bool flag = false;
    for (int i = 0; i < current.Request.Cookies.Count; i++)
    {
        HttpCookie httpCookie2 = current.Request.Cookies.Get(i);
        if (httpCookie2.Name == "FedAuth" && !flag)
        {
            flag = true;
            httpCookie2.Domain =  WebConfigurationManager.AppSettings["yourdomain"];
        }
    }
    if (httpCookie != null)
    {
        httpCookie.Value = value;
        current.Response.Cookies.Remove("WSS_KeepSessionAuthenticated");
        current.Response.Cookies.Add(httpCookie);
    }
    HttpCookie httpCookie3 = current.Request.Cookies["MSOWebPartPage_AnonymousAccessCookie"];
    if (httpCookie3 != null)
    {
        httpCookie3.Value = value;
        httpCookie3.Expires = new DateTime(1970, 1, 1);
        current.Response.Cookies.Remove("MSOWebPartPage_AnonymousAccessCookie");
        current.Response.Cookies.Add(httpCookie3);
    }
    SPIisSettings iisSettingsWithFallback = site.WebApplication.GetIisSettingsWithFallback(site.Zone);
    if (iisSettingsWithFallback.UseClaimsAuthentication)
    {
        string iPUrl = Authentication.GetIPUrl(principal);
        if (iPUrl != string.Empty)
        {
            string str = HttpUtility.UrlEncode(SPContext.Current.Site.RootWeb.Url);
            string url = iPUrl + "?wa=wsignout1.0&wreply=" + str;
            FederatedAuthentication.SessionAuthenticationModule.SignOut();
            if (current.Session != null)
            {
                current.Session.Abandon();
            }
            current.Response.Redirect(url);
        }
        else
        {
            FederatedAuthentication.SessionAuthenticationModule.SignOut();
            int num = 0;
            foreach (SPAuthenticationProvider current2 in iisSettingsWithFallback.ClaimsAuthenticationProviders)
            {
                num++;
            }
            if (num != 1 || !iisSettingsWithFallback.UseWindowsIntegratedAuthentication)
            {
                if (current.Session != null)
                {
                    current.Session.Abandon();
                }
                SPUtility.Redirect(web.ServerRelativeUrl, 0, current);
                return;
            }
        }
    }
    if (AuthenticationMode.Forms == SPSecurity.AuthenticationMode)
    {
        FormsAuthentication.SignOut();
        if (current.Session != null)
        {
            current.Session.Abandon();
        }
        SPUtility.Redirect(web.ServerRelativeUrl, 0, current);
    }
    else if (AuthenticationMode.Windows != SPSecurity.AuthenticationMode)
    {
        throw new SPException();
    }
}

private static string GetIPUrl(IClaimsPrincipal principal)
{
    string result;
    if (principal == null)
    {
        result = string.Empty;
    }
    else
    {
        string text = string.Empty;
        try
        {
            string text2 = principal.Identity.Name.Split(new char[] {'|'})[1];
            if (SPSecurityTokenServiceManager.Local.TrustedLoginProviders[text2] != null)
            {
                text = SPSecurityTokenServiceManager.Local.TrustedLoginProviders[text2].ProviderUri.AbsoluteUri;
            }
        }
        catch (Exception ex)
        {
            // log
        }
        result = text;
    }
    return result;
}

进一步阅读:

答案 1 :(得分:0)

常规aspx页面

<html>
<head>One Head</head>
<body>
    <form runat="server">
        <table>
            <tr>
                <td>User Name:</td>
                <td>
                    <asp:TextBox ID="txtUserName" runat="server" /></td>
            </tr>
            <tr>
                <td>Password:</td>
                <td>
                    <asp:TextBox ID="txtPassword" TextMode="Password" runat="server" /></td>
            </tr>
            <tr>
                <td colspan="2">
                    <asp:Button ID="btnButton" Text="Button" OnClick="btnButton_Click" runat="server" />
                </td>
            </tr>
        </table>
    </form>
</body>
</html>

您可能无法添加Microsoft.SharePoint.identityModel,这是我的位置

C:\Windows\Microsoft.NET\assembly\GAC_MSIL\Microsoft.SharePoint.IdentityModel\v4.0_15.0.0.0__71e9bce111e9429c\Microsoft.SharePoint.IdentityModel.dll

包含列表

using System;
using Microsoft.SharePoint;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;
using Microsoft.SharePoint.IdentityModel;
using System.IdentityModel.Tokens;

按钮点击代码

protected void btnButton_Click(object sender, EventArgs e)
{
    string domn = "mydomain";

    string membershipProviderName = "membership";
    string roleProviderName = "rolemanager";
    string cookieeee = string.Format("{0}\\{1}", domn, txtUserName.Text);
    bool isAuthenticated = Authenticate(domn, txtUserName.Text, txtPassword.Text);
    if (isAuthenticated)
    {
        SecurityToken token = SPSecurityContext.SecurityTokenForFormsAuthentication(new Uri(SPContext.Current.Web.Url), 
            membershipProviderName, roleProviderName, txtUserName.Text, txtPassword.Text, 
            SPFormsAuthenticationOption.PersistentSignInRequest);
        SPFederationAuthenticationModule.Current.SetPrincipalAndWriteSessionToken(token);
        Response.Redirect("/");
    }
}

[DirectoryServicesPermission(System.Security.Permissions.SecurityAction.LinkDemand, Unrestricted = true)]
public static bool Authenticate(string domainName, string userAlias, string userPassword)
{
    try
    {
        PrincipalContext context = new PrincipalContext(ContextType.Domain, domainName);
        return context.ValidateCredentials(userAlias, userPassword, ContextOptions.Negotiate));
    }
    catch
    {
        throw;
    }
}

注意:确保在Web配置文件中设置了所有FBA配置。这只是自定义身份验证,如果在服务和Web应用程序的中央管理和Web配置中角色和成员身份设置不正确,此功能将无效。