在 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/