Abh*_*hah 1 authentication laravel laravel-5
我在 url 中传递特定资源,例如。 https://www.example.com/ {companyID}
在控制器中,我可以通过以下方式访问资源
public function index($companyID)
{
// Code Here
}
Run Code Online (Sandbox Code Playgroud)
我需要阻止用户更改 url 和从系统访问其他 companyID。目前它是开放的并且存在安全风险。我检查了 Laravel Gate 和 Policy,但没有看到如何为我的案例实施。
我真正想要的是 AuthServiceProvider 启动方法中的一些东西,它可以在继续代码之前检查用户是否真的是资源的所有者。
有什么帮助吗?
如前所述,您可以通过创建一个中间件来检查您的资源是否对登录用户可用。
在此处查看有关中间件的一些详细信息
首先,通过创建一个中间件php artisan,像这样
php artisan make:middleware AuthResource
Run Code Online (Sandbox Code Playgroud)
接下来,将其添加到您的 App\Http\Kernel.php
protected $routeMiddleware = [
...
'AuthResource' => \App\Http\Middleware\AuthResource::class,
];
Run Code Online (Sandbox Code Playgroud)
在您的路线中,您现在可以执行以下操作:
Route::get('{companyID}', ['uses' => CompanyController@index, 'middleware' => 'AuthResource']);
Run Code Online (Sandbox Code Playgroud)
这样,AuthResource无论何时调用路由,都会使用您的中间件。在您中,App\Http\Middleware\AuthResource.php您必须更改代码
public function handle($request, Closure $next)
{
return $next($request);
}
Run Code Online (Sandbox Code Playgroud)
检查资源是否对当前登录的用户可用的东西。我假设您的公司表有一个字段user_id,它将公司链接到用户。如果您的数据结构不同,则需要相应地更改代码。
public function handle($request, Closure $next)
{
if ($request->route('companyID')) {
$company = Company::find($request->route('companyID'));
if ($company && $company->user_id != auth()->user()->id) {
return redirect('/');
}
}
return $next($request);
}
Run Code Online (Sandbox Code Playgroud)
这样,我们检查具有名称的路由参数companyID是否存在,如果存在,我们检查当前登录用户是否可以使用它。如果没有companyID可用参数,则可以不受任何限制地加载页面。
这样,您可以在中间件中复制/粘贴任何参数的代码,以便中间件可以为多个资源(不仅是公司)工作。
| 归档时间: |
|
| 查看次数: |
3935 次 |
| 最近记录: |