首页 > 解决方案 > 如果用户被授权,则返回附加列 - API

问题描述

我有一个基于 Laravel 的 API,它同时处理客户端和管理端点(有两个站点,例如domain.comadmin.domain.com)。我的身份验证基于 cookie,域是<.domain.com>. 如您所见,此 cookie 对两个域都是可接受的。
我将 Eloquent Api Resources 用于转换数据层。我的when()路线检查在这里安全和正确吗?

public function toArray($request)
{
    return [
        'name' => $this->name,
        'created_at' => (string)$this->created_at,
        'status' => $this->when($request->route()->getName() === 'api.admin.users.index', $this->status)
    ];
}

在我使用之前$this->when(Auth::check(), ...),但因为我的身份验证 cookie 也可以用于客户端站点,所以可能会获取不需要的数据。我的路线:

Route::group(['prefix' => 'admin', 'as' => 'api.admin.', 'middleware' => 'auth:api'], function () {
    Route::resource('users', ...);
});

如果用户未经授权,由于中间件,他将无法获取数据。同时,授权使用(谁有未过期的 cookie)在客户端站点上时不会获得未使用的数据。
谢谢!

标签: laravel-5.6

解决方案


I think your approach is fine. The route name is something internal and the user cannot tinker with it. You could improve it by using \Route::is('api.admin.*') though. It would then work for all of your admin API routes.


推荐阅读