【问题标题】:How to distinguish a mvc 5 response from an web api 2 response?如何区分 mvc 5 响应和 web api 2 响应?
【发布时间】:2015-02-20 15:44:38
【问题描述】:

我的情况是这样的: 我在同一个项目中使用 mvc5 和 webapi2。我开始使用 mvc,由于需要身份验证和授权功能,我决定使用身份。然后,由于需求的变化,我需要实现一个 Web 服务,所以我决定使用 webapi2,但它也必须经过身份验证,所以我选择了基本授权作为我的身份验证方法。为此,我使用了自定义身份验证过滤器。每次出现问题(“无凭据”、“无效凭据”)时,此过滤器都会通过上下文结果属性返回未经授权的结果:

context.Result = new UnauthorizedResult(new AuthenticationHeaderValue[] { new AuthenticationHeaderValue("Basic") }, context.Request);

这实际上通过响应发送了 401 状态代码(我使用调试器检查了它)。问题是在我的客户中,我收到了 200 状态码。我想这是因为我收到了登录页面,而这一切都是因为我开始配置我的 mvc 应用程序时设置的这段代码:

app.UseCookieAuthentication(new CookieAuthenticationOptions
{
        AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
        LoginPath = new PathString("/Cuenta/Login"),
});

不知何故,在某些上下文管道中,我未经授权的 webapi 响应被捕获并视为来自 mvc 控制器的响应。那么请问,我如何避免这种情况?当我的 Web 服务尝试获取安全资源时,我需要接收 401 状态代码,但我仍然需要在我的应用程序的 mvc 部分中为我的安全资源提供“如果安全则返回登录”功能。

对不起,我是新手,也很抱歉我的写作。谢谢。

【问题讨论】:

    标签: c# asp.net-mvc authentication asp.net-web-api owin


    【解决方案1】:

    当且仅当您的 web-api 路由而不是您的 MVC 包含 /api/ 时,您可以通过创建自定义 CookieAuthenticationOptions.Provider.OnApplyRedirect 来解决它,如下所示:

    var urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext);
    var provider = new CookieAuthenticationProvider();
    var originalHandler = provider.OnApplyRedirect;
    
    provider.OnApplyRedirect = context =>
    {
        if (!HttpContext.Current.Request.Url.AbsoluteUri.Contains("/api/"))
        {
            var routeValues = new RouteValueDictionary();
            var uri = new Uri(context.RedirectUri);
            var returnUrl = HttpUtility.ParseQueryString(uri.Query)[context.Options.ReturnUrlParameter];
            routeValues.Add(context.Options.ReturnUrlParameter, returnUrl);
            per.Action("login", "account", routeValues);
            context.RedirectUri = newUri;
            originalHandler.Invoke(context);
        }
    };
    
    app.UseCookieAuthentication(new CookieAuthenticationOptions
    {
        AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
        LoginPath = new PathString(urlHelper.Action("Login", "Account")),
        Provider = provider
    });
    

    【讨论】:

    • 谢谢。我要检查这个替代方案,似乎比我现在使用的临时解决方案更合适。我所做的是在设置app.userCookieAuthentication... 块之前在我的owin 启动类中使用app.useWebApi(config) 启动我的webapi 服务。
    猜你喜欢
    • 1970-01-01
    • 2013-12-02
    • 2016-09-06
    • 2015-09-15
    • 1970-01-01
    • 1970-01-01
    • 2020-05-03
    • 2017-02-23
    • 1970-01-01
    相关资源
    最近更新 更多