2

我正在为 Microsoft 考试而学习,并且正在处理一些示例问题。我有这个问题:

“您正在开发一个配置为使用成员资格和角色提供程序的 ASP.NET Web 应用程序。

您需要允许所有用户执行 HTTP GET,但必须只允许名为 Moderator 的用户执行 POST 操作。您应该将哪个配置添加到 web.config 文件中?”

<authorization>
  <deny verbs="POST" users="*" />
  <allow verbs="POST" users="Moderator" />
  <allow verbs="GET" users="*" />
</authorization>

<authorization>
  <allow verbs="GET" users="*" />
  <allow verbs="POST" users="Moderator" />
  <deny verbs="POST" users="*" />
</authorization>

还有另外两个答案,但它们显然是错误的,所以我没有在这里复制它们。

我可以发现两组规则之间的唯一区别是规则的放置顺序。

正确答案是第二组规则。这里的规则首先允许“主持人”的 POST 访问,然后为其他所有人删除它。这对我来说似乎违反直觉 - 给 1 人特权,然后从每个人那里删除该特权,但之后 1 人仍然拥有特权。

如果第一组规则更有意义的话——首先拒绝所有人,然后有选择地授予个人访问权限。显然这是错误的!

谁能解释为什么会这样,以便我能更好地理解这一点?

4

2 回答 2

4

这只是先到先得的情况。ASP.NET 按顺序处理规则,直到找到匹配的规则,因此在第一种情况下,deny它将POST 到达allow.

If anything the first set of rules makes more sense - first deny everyone then selectively give access to individuals.

That's not quite how it works. The rules are checked per request, therefore, what the first rules are basically saying is:

  1. Deny all POST requests from everyone.
  2. Allow POST requests for Moderator.
  3. Allow GET requests for everyone.

All in that order. The problem here is when Moderator sends in a POST request, it will match the first rule (as it's for everyone) and be denied. However, the second scenario is saying:

  1. Allow GET requests for everyone.
  2. Allow POST requests for Moderator.
  3. Deny POST requests for everyone.

So when Moderator sends a Post request, it will match the 2nd rule and allow the request to continue. If anyone else sends in a POST request, they will hit the 3rd rule and be denied.

于 2012-08-31T08:57:38.460 回答
1

The rules are evaluated in order, and the first rule that matches the current "set of attributes" (=request type, user is authenticated or not, user roles etc) is used. From MSDN:

Given a set of merged rules for an application, ASP.NET starts at the head of the list and checks rules until the first match is found. The default configuration for ASP.NET contains an element, which authorizes all users. (By default, this rule is applied last.) If no other authorization rules match, the request is allowed. If a match is found and the match is a deny element, the request is returned with the 401 HTTP status code. If an allow element matches, the module allows the request to be processed further.

于 2012-08-31T09:10:23.440 回答