Fully disable cookies in Laravel 4 API

前端 未结 7 508
余生分开走
余生分开走 2020-12-14 04:58

I am using Laravel to build a RESTful API. I use Basic HTTP Auth (Authenticate header), with this filter:



        
7条回答
  •  萌比男神i
    2020-12-14 05:32

    I'm developing an API using laravel, so definitely I don't want to use the cookies. However, I do want to use the sessions mechanism for APIs that require authentication.

    So, I'm using the sessions.driver = "file"

    To be able to use the mechanism, but allow to override the cookie set, after much debugging, I found out that there is some hardwiring at the Middleware class, but through the magic of filters, you can disable the feature right before the cookie is set.

    So, on filters.php, I created the following filter, and added as an after filter of my route group

    /*
    |--------------------------------------------------------------------------
    | Custom Filter to remove the session cookie
    |--------------------------------------------------------------------------
    |
    | By default, if session driver is other than `null` or `array`, it will
    | create a cookie and pass the encrypted session id so that it can be used
    | across web requests.
    | However, since our application is an API, we dont need the cookie, but
    | we still want to be able to use the session functionality, so to allow
    | this, we just need to set the driver to `array` right before the 
    | dispatcher gets to the point to add the session cookie.
    | 
    | This is the Laravel call stack
    | \Illuminate\Session\Middleware::handle()
    |   -> \Illuminate\Session\Middleware::addCookieToResponse()
    |        -> \Illuminate\Session\Middleware::sessionIsPersistent()
    |
    | All session handling and file storage has happened before sessionIsPersistent()
    | is called, so we are safe to add an `after` filter that will reset
    | the driver in the configuration and thus preventing this specific
    | cookie to be added, all other previously added cookies will be 
    | kept (if any added) and thus sent as part of the response.
    */
    Route::filter('session.cookie.remove', function(){
        // Has to be 'array' because null, will prevent from writing sessions
        Config::set('session.driver', 'array');
    });
    

    Note: the only case where this filter will not get called and thus producing the cookie, is if an exception occurs, in which case you may want to update the config on your error handler as well (default error handler if you haven't overwritten laravel's). To override, look at app/start/global.php

提交回复
热议问题