26

ユーザーが Windows 認証またはフォーム認証を使用して ASP.NET MVC Web アプリケーションに対して認証できるようにする必要があるというシナリオがあります。ユーザーが内部ネットワーク上にいる場合は Windows 認証を使用し、外部に接続している場合はフォーム認証を使用します。このために ASP.NET MVC Web アプリケーションをどのように構成すればよいかという質問をする人をかなり多く見かけましたが、完全な説明は見つかりませんでした。

これがどのように行われるかについて、誰かがコード例で詳細な説明を提供できますか?

ありがとう。

アラン・T

4

4 に答える 4

18

これは混合認証モードと呼ばれます。基本的に、単一のアプリケーション内でこれを実現することはできません。IISでは、仮想ディレクトリにWindows認証を設定すると、異なるドメインからのユーザーを受け入れなくなるためです。したがって、基本的に2つのアプリケーションが必要です。1つはWindows認証を使用し、もう1つ(メインアプリケーション)はフォーム認証を使用します。最初のアプリケーションは単一のアドレスで構成され、ドメインユーザーの認証チケットを発行することでメインアプリケーションにリダイレクトされます。

于 2010-03-13T09:08:51.437 に答える
18

これは可能です。構成を逆にして、app/root を Anonymous と Forms 認証を使用するように設定します。このように、同じ Web アプリケーション内で混合認証を構成できますが、これはトリッキーです。最初に、loginUrl="~/WinLogin/WinLogin2.aspx" を使用してフォーム認証用にアプリを構成します。MVC では、IIS によって設定された認証規則がルーティングによって上書きされるため、IIS はファイルに認証を設定できるため、aspx ページを使用する必要があります。ルート Web アプリケーションで匿名認証とフォーム認証を有効にします。root/WinLogin ディレクトリで Windows 認証を有効にし、匿名認証を無効にします。カスタム 401 および 401.2 エラー ページを追加して、アカウント/サインイン URL にリダイレクトします。

これにより、パススルーが可能なすべてのブラウザーが、Windows 統合認証を使用して自動サインインできるようになります。一部のデバイス (iPhone など) では資格情報の入力を求められますが、blackberry などの他のデバイスではサインイン ページにリダイレクトされます。

これにより、ユーザーの役割を明示的に追加する Cookie も作成され、役割ベースの承認を使用できるように汎用原則が作成されます。

WinLogin2.aspx (IIS の「ルート」Web アプリケーションの下の WinLogin ディレクトリ内) で、Windows 認証を使用するように構成され、匿名が無効で、フォームが有効になっています (オフにできないため... Windows 認証を有効にすると IIS が文句を言うことに注意してください。無視してください):

var logonUser = Request.ServerVariables["LOGON_USER"];
if (!String.IsNullOrWhiteSpace(logonUser))
{
    if (logonUser.Split('\\').Length > 1)
    {
        var domain = logonUser.Split('\\')[0];
        var username = logonUser.Split('\\')[1];

        var timeout = 30;

        var encTicket = CreateTicketWithSecurityGroups(false, username, domain, timeout);

        var authCookie = new HttpCookie(".MVCAUTH", encTicket) { HttpOnly = true };
        Response.Cookies.Add(authCookie);
    }
    //else
    //{
    // this is a redirect due to returnUrl being WinLogin page, in which logonUser will no longer have domain attached
    // ignore as forms ticket should already exist
    //}

    string returnUrl = Request.QueryString["ReturnUrl"];

    if (returnUrl.IsEmpty())
    {
        Response.Redirect("~/");
    }
    else
    {
        Response.Redirect(returnUrl);
    }
}

public static string CreateTicketWithSecurityGroups(bool rememberMe, string username, string domain, int timeout)
{
    using (var context = new PrincipalContext(ContextType.Domain, domain))
    {
        using (var principal = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, username))
        {
            var securityGroups = String.Join(";", principal.GetAuthorizationGroups());

            var ticket =
                new FormsAuthenticationTicket(1,
                                                username,
                                                DateTime.UtcNow,
                                                DateTime.UtcNow.AddMinutes(timeout),
                                                rememberMe,
                                                securityGroups,
                                                "/");

            string encTicket = FormsAuthentication.Encrypt(ticket);
            return encTicket;
        }
    }
}

IIS 7.5 では、[エラー ページ] をクリックし、次のコードを使用して、401 ページを Redirect401.htm ファイルのファイル パスに設定します。

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script>
      window.location.assign('../Account/Signin');
    </script>
</head>
<body>
</body>
</html>

AccountController で...

public ActionResult SignIn()
{
    return View(new SignInModel());
}

//
// POST: /Account/SignIn
[HttpPost]
public ActionResult SignIn(SignInModel model, string returnUrl)
{
    if (ModelState.IsValid)
    {
        if (Membership.ValidateUser(model.UserName, model.Password))
        {
            string encTicket = CreateTicketWithSecurityGroups(model.RememberMe,  model.UserName, model.Domain, FormsAuthentication.Timeout.Minutes);

            Response.Cookies.Add(new HttpCookie(".MVCAUTH", encTicket));

            //var returnUrl = "";
            for (var i = 0; i < Request.Cookies.Count; i++)
            {
                HttpCookie cookie = Request.Cookies[i];
                if (cookie.Name == ".MVCRETURNURL")
                {
                    returnUrl = cookie.Value;
                    break;
                }
            }

            if (returnUrl.IsEmpty())
            {
                return Redirect("~/");
            }

            return Redirect(returnUrl);
        }

        ModelState.AddModelError("Log In Failure", "The username/password combination is invalid");
    }

    return View(model);
}

//
// GET: /Account/SignOut
public ActionResult SignOut()
{
    FormsAuthentication.SignOut();

    if (Request.Cookies[".MVCRETURNURL"] != null)
    {
        var returnUrlCookie = new HttpCookie(".MVCRETURNURL") { Expires = DateTime.Now.AddDays(-1d) };
        Response.Cookies.Add(returnUrlCookie);
    }

    // Redirect back to sign in page so user can 
    //   sign in with different credentials

    return RedirectToAction("SignIn", "Account");
}

global.asax で:

protected void Application_BeginRequest(object sender, EventArgs e)
{
    try
    {
        bool cookieFound = false;

        HttpCookie authCookie = null;

        for (int i = 0; i < Request.Cookies.Count; i++)
        {
            HttpCookie cookie = Request.Cookies[i];
            if (cookie.Name == ".MVCAUTH")
            {
                cookieFound = true;
                authCookie = cookie;
                break;
            }
        }

        if (cookieFound)
        {
            // Extract the roles from the cookie, and assign to our current principal, which is attached to the HttpContext.
            FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value);
            HttpContext.Current.User = new GenericPrincipal(new FormsIdentity(ticket), ticket.UserData.Split(';'));
        }
    }
    catch (Exception ex)
    {
        throw;
    }
}


protected void Application_AuthenticateRequest()
{
    var returnUrl = Request.QueryString["ReturnUrl"];
    if (!Request.IsAuthenticated && !String.IsNullOrWhiteSpace(returnUrl))
    {
        var returnUrlCookie = new HttpCookie(".MVCRETURNURL", returnUrl) {HttpOnly = true};
        Response.Cookies.Add(returnUrlCookie);
    }
}

web.config

<system.web>
  <!--<authorization>
    <deny users="?"/>
  </authorization>-->
  <authentication mode="Forms">
    <forms name=".MVCAUTH" loginUrl="~/WinLogin/WinLogin2.aspx" timeout="30" enableCrossAppRedirects="true"/>
  </authentication>
  <membership defaultProvider="AspNetActiveDirectoryMembershipProvider">
    <providers>
      <add
           name="AspNetActiveDirectoryMembershipProvider"
           type="System.Web.Security.ActiveDirectoryMembershipProvider, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
           connectionStringName="ADService" connectionProtection="Secure" enablePasswordReset="false" enableSearchMethods="true" requiresQuestionAndAnswer="true"
           applicationName="/" description="Default AD connection" requiresUniqueEmail="false" clientSearchTimeout="30" serverSearchTimeout="30"
           attributeMapPasswordQuestion="department" attributeMapPasswordAnswer="division" attributeMapEmail="mail" attributeMapUsername="sAMAccountName"
           maxInvalidPasswordAttempts="5" passwordAttemptWindow="10" passwordAnswerAttemptLockoutDuration="30" minRequiredPasswordLength="7"
           minRequiredNonalphanumericCharacters="1" />
    </providers>
  </membership>
  <machineKey decryptionKey="..." validationKey="..." />
</system.web>
<connectionStrings>
  <add name="ADService" connectionString="LDAP://SERVER:389"/>
</connectionStrings>

http://msdn.microsoft.com/en-us/library/ms972958.aspxのクレジット

于 2012-01-25T19:13:54.687 に答える
4

これはおそらくこの質問の一番下にあり、決して見つからないでしょうが、私はで説明されていることを実装することができました

http://mvolo.com/iis-70-twolevel-authentication-with-forms-authentication-and-windows-authentication/

それは非常に簡単で些細なことでした。FormsAuthModule を拡張して web.config を変更するだけで、複数のアプリケーションや Cookie ハックは必要ありませんでした。

于 2013-08-22T18:47:38.097 に答える