【发布时间】:2016-01-16 19:16:33
【问题描述】:
我正在编写使用 Identity 作为授权引擎的 ASP.NET 应用程序。我编写了自定义用户和角色存储,它们似乎工作正常。但是,由于某些未知原因,尝试使用Authorize 与控制器操作的角色失败并重定向到Home/Index。操作如下所示:
[Authorize(Roles = "Admin")]
public ActionResult Manage()
{
return View();
}
重定向是静默完成的,所以我无法在任何地方挂接调试器(尤其是在运行动作之前进行动作过滤)。
我想这可能不足以诊断问题,所以只需在 cmets 中告诉我,您需要哪些额外信息,我会编辑问题。
为什么它不起作用?
编辑:Startup.cs中的配置
public void Configuration(IAppBuilder app)
{
DataProtectionProvider = app.GetDataProtectionProvider();
app.CreatePerOwinContext<ApplicationUserManager>(() => DependencyResolver.Current.GetService<ApplicationUserManager>());
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = "ApplicationCookie",
LoginPath = new PathString("/Account/Login")
});
}
编辑:另一个动作:
[AllowAnonymous]
public async Task<ActionResult> Index()
{
// This returns FALSE
if (User.IsInRole("Admin"))
System.Diagnostics.Debug.WriteLine("Ok");
var userManager = UnityConfig.Container.Resolve<ApplicationUserManager>();
// This returns TRUE
if (await userManager.IsInRoleAsync(User.Identity.GetUserId<int>(), "Admin"))
System.Diagnostics.Debug.WriteLine("Ok");
return View();
}
【问题讨论】:
-
首先,删除该属性并验证您是否正确地转到管理。授权失败应该将您发送到登录,而不是主页/索引
-
这是支持 OWIN 的应用程序吗?如果是这样,你能显示你的授权配置吗?
-
@HenkHolterman 是的,如果我将
[Authorize]替换为[AllowAnonymous],它可以正常工作 -
@TiesonT。我对OWIN很陌生,
Startup.cs中的Configuration方法是你指的方法吗? -
@Spook 如果您遵循通用模板,是的(您的编辑看起来就是这种情况)。
标签: c# asp.net asp.net-mvc asp.net-identity