1

有很多类似的问题,但这让我很难过。

如果我使用 [Authorize] 会提示输入用户名和密码,但如果我使用 [InternalAuthorizeV2] 我不会

我有一个自定义的 AuthorizeAttribute ,目前它没有做任何特别的事情(我限制了可能出错的事情)。

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
    public class InternalAuthorizeV2Attribute: AuthorizeAttribute
    {}

和我的控制器中的一个动作

   [InternalAuthorizeV2(Roles = "MobileApps_Parkingggg")]
         public ActionResult Index()
         {
             var model = new VmParking();
             return View(model);
         }

登录在不同的应用程序中处理,但它们具有相同的 Web 配置行

   <machineKey compatibilityMode="Framework20SP2" validationKey="editedOut" decryptionKey="editedOut" validation="SHA1" decryption="AES"/>
      <authentication mode="Forms">
          <forms name="emLogin" loginUrl="/Login/Index" timeout="540" protection="All" path="/"  enableCrossAppRedirects="true"  cookieless="UseCookies" />
      </authentication>
    <sessionState timeout="540" />

我知道,如果我通过使用 [Authorize] 进入页面登录,然后返回我的问题页面,我可以看到用户名,但它似乎没有调用我的客户属性。

新信息: 我的属性位于共享 DLL 中,因为它被许多应用程序使用。看来,如果我将 cs 文件复制到 web 项目,它就可以工作。不知道为什么,仍在寻找提示或提示。

4

1 回答 1

4

根据您所说,如果您使用[Authorize]但不使用[InternalAuthorizeV2].

如果设置正确,您的共享 dll 应该不会有任何区别;我有同样的工作。确保 Web 项目使用的是最新版本的 dll,并且您在共享 dll 中拥有正确的程序集引用 -System.Web.Mvc, v4.0.0.0在我的项目中。

你说它被许多应用程序使用?共享 dll 是否所有应用程序都存在相同问题,还是其中一个存在相同问题?如果它只是一个,请检查有问题的那个的参考。

如果以下测试全部正常,那么最后一个选项是,无论您在 dll 中的授权属性中做什么,都没有为该应用程序选择正确的上下文,或者使用正确的成员资格提供程序或数据库 - 您没有包括您在属性中使用的代码,因此很难知道这是否会导致问题。

测试依赖

您可以尝试将基本授权属性添加到您的共享 dll,然后在您的 Web 项目中实现另一个授权属性,该属性继承您刚刚创建的基本属性。这应该表明您已正确设置共享 dll。

// in the dll:
public class BaseAuthorizeAttribute : System.Web.Mvc.AuthorizeAttribute { ... }

// in the web project:
public class InternalAuthorizeV2Attribute : BaseAuthorizeAttribute { ... }

如果只是将它从您的 dll 项目移动到 web 项目修复它,最可能的问题是 web 项目没有使用正确版本的 dll(尝试清理并进行完全重建)或者您的 dll 引用了错误的 dll System.Web.Mvc.AuthorizeAttribute. _ 您说您已经进行了三次检查,但尝试上述调试应该可以帮助您确定是否确实如此。

调试授权方法调用

如果这不起作用,请尝试将以下覆盖方法添加到一个非常简单的属性,并查看是否在调用base.OnAuthorization. 如果你不这样做,那么它可能不是导致你的问题的实际属性。

[AttributeUsageAttribute(AttributeTargets.Class|AttributeTargets.Method, 
  Inherited = true, AllowMultiple = true)]
public class InternalAuthorizeV2Attribute : System.Web.Mvc.AuthorizeAttribute {
  protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext) {
    return false; // breakpoint here, and this should force an authorization failure
  }
  public override void OnAuthorization(System.Web.Mvc.AuthorizationContext filterContext)
  {
    base.OnAuthorization(filterContext); // breakpoint here
  }
}

这应该完全阻止任何用户访问操作。如果这不起作用,那么您知道问题不在于您的属性,而是您的属性没有被应用。

您还可以将以下内容添加到您的控制器并检查它是否在授权属性之前被命中:

protected override void OnAuthorization(AuthorizationContext filterContext) {
    base.OnAuthorization(filterContext);
}

授权链

请注意,您已将属性附加到 Action 方法,因此只有在链中较早的授权属性(例如全局过滤器或控制器属性)尚未阻止用户被授权时才会命中它(请参阅我的回答here ),或者过早地返回一个 ActionResult 阻止链到达您的 Action 属性。但是,如果只是将其从 dll 移至项目使其工作,则这不太可能是问题。同样,AllowAnonymous从您所说的内容来看,您不太可能在错误的地方。

于 2013-06-19T13:20:31.813 回答