ASP.NET Core 2.1 : 十四.靜態檔案與訪問授權、防盜鏈
ASP.NET Core 2.1 : 十四.靜態檔案與訪問授權、防盜鏈
我的網站的圖片不想被公開瀏覽、下載、盜鏈怎麼辦?本文主要通過解讀一下ASP.NET Core對於靜態檔案的處理方式的相關原始碼,來看一下為什麼是wwwroot資料夾,如何修改或新增一個靜態資料夾,為什麼新增的資料夾名字不會被當做controller處理?訪問授權怎麼做?
一、靜態資料夾
所謂靜態檔案,直觀的說就是wwwroot目錄下的一些直接提供給訪問者的檔案,例如css,圖片、js檔案等。 當然這個wwwroot目錄是預設目錄,
這個是在Main->CreateDefaultBuilder的時候做了預設設定。
public static class HostingEnvironmentExtensions { public static void Initialize(this IHostingEnvironment hostingEnvironment, string contentRootPath, WebHostOptions options) { //省略部分程式碼 var webRoot = options.WebRoot; if (webRoot == null) { // Default to /wwwroot if it exists. var wwwroot = Path.Combine(hostingEnvironment.ContentRootPath, "wwwroot"); if (Directory.Exists(wwwroot)) { hostingEnvironment.WebRootPath = wwwroot; } } else { hostingEnvironment.WebRootPath = Path.Combine(hostingEnvironment.ContentRootPath, webRoot); } //省略部分程式碼 } }
二、處理方式
前文關於中介軟體部分說過,在Startup檔案中,有一個 app.UseStaticFiles() 方法的呼叫,這裡是將靜態檔案的處理中介軟體作為了“處理管道”的一部分,
並且這個中介軟體是寫在 app.UseMvc 之前, 所以當一個請求進來之後, 會先判斷是否為靜態檔案的請求,如果是,則在此做了請求處理,這時候請求會發生短路,不會進入後面的mvc中介軟體處理步驟。
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseCookiePolicy(); app.UseAuthentication(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); }
三、新增靜態檔案目錄
除了這個預設的wwwroot目錄,需要新增一個目錄來作為靜態檔案的目錄,可以Startup檔案的 app.UseStaticFiles() 下面繼續use,例如下面程式碼
app.UseFileServer(new FileServerOptions { FileProvider = new PhysicalFileProvider( Path.Combine(Directory.GetCurrentDirectory(), "NewFilesPath")), RequestPath = "/NewFiles" });
含義就是指定應用程式目錄中的一個名為“NewFilesPath”的資料夾,將它也設定問靜態檔案目錄, 而這個目錄的訪問路徑為"/NewFiles"。
例如資料夾"NewFilesPath"下面有一個test.jpg, 那麼我們可以通過這樣的地址來訪問它:http://localhost:64237/NewFiles/test.jpg。
四、中介軟體的處理方式
靜態檔案的處理中介軟體為StaticFileMiddleware,主要的處理方法 Invoke 程式碼如下
public async Task Invoke(HttpContext context) { var fileContext = new StaticFileContext(context, _options, _matchUrl, _logger, _fileProvider, _contentTypeProvider); if (!fileContext.ValidateMethod()) { _logger.LogRequestMethodNotSupported(context.Request.Method); } else if (!fileContext.ValidatePath()) { _logger.LogPathMismatch(fileContext.SubPath); } else if (!fileContext.LookupContentType()) { _logger.LogFileTypeNotSupported(fileContext.SubPath); } else if (!fileContext.LookupFileInfo()) { _logger.LogFileNotFound(fileContext.SubPath); } else { // If we get here, we can try to serve the file fileContext.ComprehendRequestHeaders(); switch (fileContext.GetPreconditionState()) { case StaticFileContext.PreconditionState.Unspecified: case StaticFileContext.PreconditionState.ShouldProcess: if (fileContext.IsHeadMethod) { await fileContext.SendStatusAsync(Constants.Status200Ok); return; } try { if (fileContext.IsRangeRequest) { await fileContext.SendRangeAsync(); return; } await fileContext.SendAsync(); _logger.LogFileServed(fileContext.SubPath, fileContext.PhysicalPath); return; } catch (FileNotFoundException) { context.Response.Clear(); } break; case StaticFileContext.PreconditionState.NotModified: _logger.LogPathNotModified(fileContext.SubPath); await fileContext.SendStatusAsync(Constants.Status304NotModified); return; case StaticFileContext.PreconditionState.PreconditionFailed: _logger.LogPreconditionFailed(fileContext.SubPath); await fileContext.SendStatusAsync(Constants.Status412PreconditionFailed); return; default: var exception = new NotImplementedException(fileContext.GetPreconditionState().ToString()); Debug.Fail(exception.ToString()); throw exception; } } await _next(context); }
當HttpContext進入此中介軟體後會嘗試封裝成StaticFileContext, 然後對其逐步判斷,例如請求的URL是否與設定的靜態目錄一致, 判斷檔案是否存在,判斷檔案型別等,
若符合要求 ,會進一步判斷檔案是否有修改等。
五、靜態檔案的授權管理
預設情況下,靜態檔案是不需要授權,可以公開訪問的。
因為即使採用了授權, app.UseAuthentication(); 一般也是寫在 app.UseStaticFiles() 後面的,那麼如果我們想對其進行授權管理,首先想到可以改寫 StaticFileMiddleware 這個中介軟體,
在其中新增一些自定義的判斷條件,但貌似不夠友好。而且這裡只能做一些大類的判斷,比如請求的IP地址是否在允許範圍內這樣的還行,如果要根據登入使用者的許可權來判斷(比如使用者只能看到自己上傳的圖片)就不行了,
因為許可權的判斷寫在這個中介軟體之後。所以可以通過Filter的方式來處理,首先可以在應用目錄中新建一個"images"資料夾, 而這時就不要把它設定為靜態檔案目錄了,這樣這個"images"目錄的檔案預設情況下是不允許訪問的,
然後通過Controller返回檔案的方式來處理請求,如下程式碼所示
[Route("api/[controller]")] [AuthorizeFilter] public class FileController : Controller { [HttpGet("{name}")] public FileResult Get(string name) { var file = Path.Combine(Directory.GetCurrentDirectory(), "images", name); return PhysicalFile(file, "application/octet-stream"); } }
在AuthorizeFilter中進行相關判斷,程式碼如下
public class AuthorizeFilter: ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext context) { base.OnActionExecuting(context); if (context.RouteData.Values["controller"].ToString().ToLower().Equals("file")) { bool isAllow = false;//在此進行一系列訪問許可權驗證,如果失敗,返回一個預設圖片,例如logo或不允許訪問的提示圖片 if (!isAllow) { var file = Path.Combine(Directory.GetCurrentDirectory(), "images", "default.png"); context.Result = new PhysicalFileResult(file, "application/octet-stream"); } } } }
☆☆☆ 共同學習,歡迎拍磚;轉載請註明出處,謝謝。☆☆☆