ASP MVC单应用程序多域身份验证

时间:2015-10-01 10:39:07

标签: asp.net-mvc authentication cross-domain

我有一个客户特别要求的以下严格方案:使用Asp.NET MVC4的单个网站,可通过具有单点登录机制的各种域访问。

我已设法通过在webconfig中指定二级域

来对子域进行表单身份验证工作
 <authentication mode="Forms">
  <forms name="SingleSignOn" loginUrl="/Login/LoginRedirect" timeout="10" slidingExpiration="false" domain="domain.ml"  cookieless="UseCookies" enableCrossAppRedirects="true">
    <credentials passwordFormat="SHA1" />
  </forms>
</authentication>

同样在登录逻辑中调用FormsAuthentication.SetAuthCookie时,我也指定了第二级域:

 System.Web.HttpCookie MyCookie = System.Web.Security.FormsAuthentication.GetAuthCookie(lName, false);
                    MyCookie.Domain = lSecondLevelDomain;
                    FormsAuthentication.SetAuthCookie(lName, false);

在不同的域中,这不起作用,因为实际域与web.config中指定的域不匹配,也不与cookie匹配。

目标是:

用户访问domain1.com 用户重定向到logindomain.com并创建了经过身份验证的cookie 用户重定向回domain1.com

用户始终会重定向到“登录域”,使用该域创建Cookie,并始终使用跨域的相同Cookie进行身份验证。

是否可以覆盖Authorize属性的逻辑,以便允许使用登录域的cookie而不是用户最初使用的域进行授权?

1 个答案:

答案 0 :(得分:0)

在深入编程之前,请先查看How does SO's new auto-login feature work?以了解如何实现此类方案。

然后查看Forms Authentication Across ApplicationsSingle Sign On (SSO) for cross-domain ASP.NET applications。现在您可以按照自己的意愿达到目的:)

如果您强烈考虑结果绝对返回URL的有效性,也可以使用以下代码:

public class Startup {
    public void Configuration(IAppBuilder app) {
        app.UseCookieAuthentication(new CookieAuthenticationOptions {
            AuthenticationMode = AuthenticationMode.Active,
            LoginPath = new PathString("/account/login"),
            LogoutPath = new PathString("/account/logout"),
            Provider = new CookieAuthenticationProvider { OnApplyRedirect = ApplyRedirect },
        });
    }

    private static void ApplyRedirect(CookieApplyRedirectContext context) {
        Uri absoluteUri;
        if (Uri.TryCreate(context.RedirectUri, UriKind.Absolute, out absoluteUri)) {
            var path = PathString.FromUriComponent(absoluteUri);
            if (path == context.OwinContext.Request.PathBase + context.Options.LoginPath)
                context.RedirectUri = "http://accounts.domain.com/login" +
                    new QueryString(
                        context.Options.ReturnUrlParameter,
                        context.Request.Uri.AbsoluteUri);
                        // or use context.Request.PathBase + context.Request.Path + context.Request.QueryString
        }

        context.Response.Redirect(context.RedirectUri);
    }
}
相关问题