ASP.NET Controller 上未经授权的访问应返回 401 而不是 200 以及登录页面

标签 asp.net asp.net-mvc asp.net-identity asp.net-core asp.net-core-mvc

ASP.NET 5 应用程序中,我配置了 MVC 和 Identity 框架,如下所示:

app.UseMvc(config=>{
    config.MapRoute("Default", "{controller}/{action}/{id?}", new
            {
                controller = "Home",
                action = "Index"
            });
});

并添加身份服务:

   services.AddAuthentication();
   services.AddAuthorization();

   services.AddIdentity<CrmUser, CrmUserRole>(config => { 
         config.User.RequireUniqueEmail = true;
          })
          .AddUserStore<MongoUserStore>()
          .AddRoleStore<MongoUserStore>()
          .AddDefaultTokenProviders();

 app.UseIdentity()
    .UseCookieAuthentication(i => { i.LoginPath = "/Account/Login";});

示例定义如下:

public class MyApiController : Microsoft.AspNet.Mvc.Controller
{
    [Authorize]
    public async Task<ActionResult> Foo()
    {
        return Ok();
    }
}

这工作正常,但我也有一些我想以 API 方式使用的 Controller 。在 ASP.NET 5 中,它们都具有相同的基类,因此 API 和 View Controller 之间没有区别。

因此,当调用需要授权的未经授权的 api 时,我会收到 HTTP 200 和登录页面,而不是 HTTP 401

Shawn Wildermuth 的博客文章中我发现了这个

services.AddCookieAuthentication(config =>
    {
        config.LoginPath = "/Auth/Login";
        config.Events = new CookieAuthenticationEvents()
        {
            OnRedirect = ctx =>
            {
                if (ctx.Request.Path.StartsWithSegments("/api") &&
                ctx.Response.StatusCode == 200)
                {
                    ctx.Response.StatusCode =     (int)HttpStatusCode.Unauthorized;
                    return Task.FromResult<object>(null);
                }
                else
                {
                    ctx.Response.Redirect(ctx.RedirectUri);
                    return Task.FromResult<object>(null);
                }
            }
        };
    });

但这真的是预期的方式吗?对我来说这有点味道。

最佳答案

此问题已在 RC1 中修复。

在此处查看 GitHub 评论:Issue

要升级到RC1,请转到http://get.asp.net

更确定的是,您还可以在获取最新版本之前清除 %userprofile%\.dnx\ 文件夹。

关于ASP.NET Controller 上未经授权的访问应返回 401 而不是 200 以及登录页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33375322/

相关文章:

asp.net - 在 ASP.NET 中自动进行 HtmlEncode

asp.net - 为什么 Request.IsSecureConnection 在预期为 true 时返回 false

c# - 无法让 Foundation 的 Abide 与 Html Helper 表单一起使用

asp.net-mvc - Entity Framework /Glimpse 持续时间差异

asp.net - 通过 WEB API 使用 ASP.NET Identity 进行本地登录

c# - ASP.NET Core Identity 3 Cookie 超时

asp.net - 帮助 CSS 定位

c# - ASP.NET Web 应用程序的推荐体系结构是什么?

c# - 机器人程序/蜘蛛程序可以使用 Cookies 吗?

c# - ASP.NET Identity 从 AspNetUsers 表中删除列