如何检查用户是否在 accessing/viewing 文件系统 public 磁盘中的文件之前通过身份验证?

How do I check whether a user is authenticated before accessing/viewing a file from the filesystem public disk?

我正在使用 laravel 文件系统来存储和检索文件。 public/storage 符号链接到 storage/app/public。在 storage/app/public 目录下,我有两个包含相应文件的文件夹(以便可以在浏览器中访问这些文件):

  1. 徽标
    • ABC.png
    • DEF.png
  2. 受保护的文件
    • file1.pdf
    • file2.pdf

当用户尝试访问 protected-files 目录中的文件时,我想检查该用户是否已通过身份验证。我们能做到吗?

我按照link中的答案做了,但是一点效果都没有。

web.php

Route::get('storage/protected-files/{file}', function() {
   //logic to check whether the user is authenticated
})->where(['file' => '.*']);

在访问文件之前,您可以简单地检查用户是否使用此代码进行了身份验证。

Auth::check():

storage/protected-files 路径是指文件在服务器上的位置,但实际上 public 世界可以访问 http://example.com/file-name.pdf。 laravel 中的路由旨在处理 URL。所以应该尝试:

Route::get('/{file}', function() {
    //check whether the user is authenticated
    if (!auth()->user()) { //    or may use Auth::check();
        return 'unauthorized';
    }
})->where(['file' => '.*']);

Web 服务器将 return 如果文件存在于 /public 目录中,请求甚至不会到达 laravel。

因此您必须将文件从 /storage/app/public 目录移动到 /storage/app/xxxx 目录。并进行相同的验证。

可以使用'local'磁盘写入storage/app目录,所以写入文件时必须指定目录。