我对OWIN身份验证完全陌生,我一定是误解了一切的工作原理,但是我在任何地方都找不到提到这一点的地方.

我只想使用一个中心域进行身份验证.如果有人试图在未经身份验证的情况下访问apps.domain.com,他们将被重定向到accounts.domain.com/login,以便将所有身份验证分离到其自己的域和应用程序中.这在MVC4表单认证中非常简单,您可以指定完整的URL,但在OWIN中似乎没有.

Startup.Auth.cs年内:

app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    LoginPath = new PathString("/account/login")
}

使用CookieDomain选项设置cookie时,很容易指定域.然而,当您指定要重定向到的登录路径时,它必须与当前应用程序相关,那么我该如何实现MVC4表单身份验证中如此简单的功能呢?

在没有深入了解OWIN身份验证的情况下,经过几个小时的搜索,我找不到任何解决这个问题的方法.

推荐答案

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);
            }
        }

        context.Response.Redirect(context.RedirectUri);
    }
}

如果apps.domain.com是唯一可能的返回URL基数,您应该强烈考虑将context.Request.Uri.AbsoluteUri替换为context.Request.PathBase + context.Request.Path + context.Request.QueryString,并在您的身份验证服务器中构建一个绝对返回URL,以保护您的应用程序不受滥用重定向的影响.

希望这能有所帮助;)

EDIT:您可能会问自己,为什么我不使用context.RedirectUri属性直接应用重定向.事实上,ICookieAuthenticationProvider.ApplyRedirect负责多个重定向,与登录和注销流相对应(是的,我知道,它打破了单一责任原则……).但还有更糟糕的情况:context.RedirectUri既可以表示身份验证端点在登录流开始时的绝对URL,也可以表示最终浏览器的目的地(即.真正的相对"返回URL"),当cookie被有效地发送回浏览器时…这就是为什么我们需要确保context.RedirectUri是绝对的,并且对应于注册的context.Options.LoginPath.

Asp.net相关问答推荐

Stimulsoft 没有在智能手机中显示正确的 pdf 字体

在 ASP.Net 中使用 Page_Load 和 Page_PreRender

如何将 JQuery 与母版页一起使用?

Azure 自定义控制器/API .Net 后端

ASP.NET 控件无法在 Visual Studio 2008 的代码隐藏中引用

无法加载文件或程序集 'System.Web.Mvc,版本 = 3.0.0.0,Elmah.MVC 问题

返回值使用 String result=Command.ExecuteScalar() 结果返回 null 时发生错误

显示单选按钮列表内联

Owin.IAppBuilder不包含MapSignalR的定义

如何在不预编译的情况下使用命令行msbuild部署VS2012网站项目?

MVC 4 - Razor - 将变量传递到 href url

回发不适用于 aspx 页面作为默认文档

有没有办法在没有异常类的情况下抛出自定义异常

ASP.NET Excel 导出编码问题

如何判断字符串的第一个字符是否是字母,C#中的任何字母

通过 CultureInfo 格式化字符串

为什么 Controls 集合不提供所有 IEnumerable 方法?

Page.IsPostBack 和 Page.IsCallBack 有什么区别?

DataTable 不包含 AsEnumerable 的定义

如何检索 X509Store 中的所有证书