ASP.NET Core 2.1 : 十四.靜態文件與訪問授權、防盜鏈


我的網站的圖片不想被公開瀏覽、下載、盜鏈怎么辦?本文主要通過解讀一下ASP.NET Core對於靜態文件的處理方式的相關源碼,來看一下為什么是wwwroot文件夾,如何修改或新增一個靜態文件夾,為什么新增的文件夾名字不會被當做controller處理?訪問授權怎么做?(ASP.NET Core 系列目錄

一、靜態文件夾

所謂靜態文件,直觀的說就是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");

                }
            }
        }
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM