简体   繁体   English

Laravel 中可选的身份验证中间件

[英]Auth middleware optional in Laravel

I have my controller ExampleController :我有我的 controller ExampleController

class ExampleController extends Controller
{
    function __construct()
    {
        $this->middleware('auth:student')->only(['store', 'update', 'destroy']);
    }

    public function index()
    {
        if(CheckUser::student()) {
            dd("Is student");
        }
        dd("Isn't student");
    }

    /**
     * Another method's not relevant.
     **/
}

I'm trying to add some logic if is student.如果是学生,我正在尝试添加一些逻辑。 But have one problem, I just can access: Auth::user() if I set the middleware.但是有一个问题,如果我设置中间件,我只能访问: Auth::user() But this specific method can be accessed without has logged in.但是这个特定的方法可以在没有登录的情况下访问。

My question我的问题

Is possible to create a not required middleware for what if logged get user information?如果记录获取用户信息,是否可以创建一个不需要的中间件?

Note : I'm using Laravel passport with multi auth.注意:我正在使用具有多重身份验证的 Laravel 护照。

If you want to protect specific methods that are in your controller and leave out others in the same controller如果您想保护 controller 中的特定方法,并在同一 controller 中省略其他方法

You may try to protect your endpoint on the routes files (api.php or web.php) rather than on the Constructor您可以尝试在路由文件(api.php 或 web.php)上保护您的端点,而不是在构造函数上

//protected routes
Route::group(['middleware' => 'auth:api'], function () {
    Route::post('customer/picture/add', 'Mobile\AuthController@addProfilePicture');
    Route::post('customer/phone/update', 'Mobile\AuthController@updatePhoneNumber');
});

//unprotected routes
Route::get('customer/login', 'Mobile\AuthController@getLoginForm');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM