在 ASP.NET MVC 網站觀察到奇特行為:.css、.js 等靜態檔案可匿名存取,存取 MVC Action 則要登入,有趣的是網站上有個 HttpHandler (.axd) 也能匿名存取。

一時之間有點迷惑,花了點時間重現狀況,找出原理解惑。

使用 Visual Studio 建立新 ASP.NET 網站專案,啟用 MVC 及 WebForm,在根目錄額外加入 text.txt 靜態文字檔及 WebForm.aspx:

<%@ Page Language="C#" %>
<script runat="server">
    void Page_Load(object sender, EventArgs e) 
    {
        Response.Write("WebForm");
        Response.End();
    }
</script>

HomeController.cs 的 Index Action 則簡單傳回 MVC 字樣:

using System.Web.Mvc;

namespace AuthTest.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            return Content("MVC");
        }
    }
}

另外新增 Models/MyHttpHandler.cs 實作 IHttpHandler:

using System;
using System.Web;

namespace AuthTest.Models
{
    public class MyHttpHandler : IHttpHandler
    {
        #region IHttpHandler Members

        public bool IsReusable
        {
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {
            context.Response.Write("Handler");
            context.Response.End();
        }

        #endregion
    }
}

web.config 掛上 test.axd 設定:

<system.webServer>
<handlers>
  <add name="TestAxd" verb="GET,POST" path="test.axd" type="AuthTest.Models.MyHttpHandler,AuthTest" />
</handlers>
</system.webServer>

實測結果如下圖:

成功重現 text.txt、WebForm.aspx、test.axd 都可以匿名存取,但 MVC Home/Index 不行。

揭曉達成上述效果的關鍵。

首先,IIS 要同時啟用匿名及 Windows 驗證:

而專案裡有個 App_Start/FilterConfig.cs 註冊了全域 Filter:(執行時機為 Global.asax.cs Application_Start() 時呼叫 FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); )

using System.Web.Mvc;

namespace AuthTest
{
    public class FilterConfig
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new AuthorizeAttribute());
        }
    }
}

註冊 AuthorizeAttribute 後將限定 ASP.NET MVC 需登入才能存取,但其管控範圍並不包含靜態檔案(js、css、png... 等)、WebForm 以及 HttpHandler。引用 Profession ASP.NET MVC 4 一書的說明證實此點:

It's important to keep in mind that a global filter applies only to MVC controller actions. It doesn't secure Web Forms, static content, or other ASP.NET handlers.

IAuthorizationFilter 管不到 WebForm,要從 web.config 下手。在 web.config 加上 authorization/deny users="?" 後,curl 下載 WebForm.aspx 與 test.axd 會得到 HTTP 401,但靜態檔 text.txt 仍可匿名存取。

	<authorization>
		<deny users="?" />
	</authorization>
  </system.web>

若在 IIS 管理介面停用匿名存取,只留 Windows 整合驗證,則所有存取都會吐回 HTTP 401。

演練完畢,重新釐清觀念,收工。

This article demostrates that AuthorizeAttribute only enable authorization of MVC controllers, but not including static contents, Web Forms, and ASP.NET handdlers.


Comments

Be the first to post a comment

Post a comment