【问题标题】:Is ist ok to throw a HttpException(401) in custom AuthorizeAttribute?可以在自定义 AuthorizeAttribute 中抛出 HttpException(401) 吗?
【发布时间】:2016-01-28 10:05:56
【问题描述】:

我有一个自定义 AuthorizeAttribute:

public class MyAuthAttribute:AuthorizeAttribute {
 protected override bool AuthorizeCore(HttpContextBase httpContext) {
    return CurrentUser.Roles.Contains(this.Roles);
 }
}

现在return Currentuser.Roles 工作得很好。如果返回 false,浏览器会显示 401。

但我想添加其他信息,例如要求的角色。所以我会自己抛出一个异常,而不是 return:

throw new httpException(401,string.Format("User should have been in one of the following roles: {0}",this.Roles);

可以在 AuthorizeAttribute 中抛出 401-Exception 而不是只返回 false 吗?还是有其他(更好的)方法可以将这些信息发送到浏览器?

【问题讨论】:

  • 您确定要向恶意用户公开这些附加信息吗?
  • 是的。用户应该能够知道缺少哪些组,然后请求管理员授予他访问权限。

标签: c# asp.net-mvc error-handling authorize-attribute custom-authentication


【解决方案1】:

如果您要发送 401,则只需发送带有 WWW-Authenticate 标头的普通 401(如果您不使用使用 WWW-Authenticate 的身份验证形式,则 401 完全不合适)。如果您想提供额外信息,请在与该 401 一起使用的自定义 HTML 响应的正文中执行此操作(仅当用户取消身份验证提示时才会显示)。

对于您可以做某事但选择不允许特定用户这样做的任何其他情况,请使用 403。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-15
    • 2021-10-19
    • 2011-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-24
    相关资源
    最近更新 更多