Disable “Cookie” header when responding json

霸气de小男生 提交于 2019-12-04 08:44:36
Mārtiņš Briedis

Ok, it turns out, that it is no longer possible to change session/cookie driver within route middlewares. You have to specify the middleware BEFORE Illuminate\Session\Middleware\StartSession middleware.

Solution: 1. Create your own middleware:

class ApiSession implements Middleware{
    public function handle($request, Closure $next){
        $path = $request->getPathInfo();

        if(strpos($path, '/api/') === 0){
            \Config::set('session.driver', 'array');
            \Config::set('cookie.driver', 'array');
        }

        return $next($request);
    }
}
  1. Add it in Kernel file (app/Http/Kernel.php) before Session middleware:

[..] ApiSession::class, // Check if an API request. If so, set session, cookie drivers Illuminate\Session\Middleware\StartSession::class, [..]

The bad part is that you cannot use it with route groups. You have to check for your self if this middleware is applied by checking the current url path.

Anyway if you want to disable cookies on all request, you can remove the if statement as is:

// myapp/app/Http/Middleware/ApiSession.php

<?php

namespace App\Http\Middleware

use Closure;

class ApiSession {

         public function handle($request, closure $next){

               \Config::set('session.driver', 'array');
               \Config::set('cookie.driver', 'array');

         }
}

And remember to add/modify your kernel.php as showed "Mārtiņš Briedis". Now, your app don't use cookies.

this code Config::set('session.driver' , 'array') disable laravel_session ... that in set-cookie Header set and above code disabled that HEADER , but another HEADER with name Set-Cookie exist for XRFF-TOKEN ,for disable this problem you should override the middleware VerifyCsrfToken .

below code add in app->Http->MiddleWare->VerifyCsrfToken.php and add this function to VerifyCsrfToken class

    protected function addCookieToResponse($request, $response)
{
    $config = config('session');        
    if ($config['driver'] == 'array' || !$this->shouldPassThrough($request))
    {        
        return $response;
    }else
    {
        $response->headers->setCookie(
            new Cookie(
                'XSRF-TOKEN', $request->session()->token(), time() + 60 * $config['lifetime'],
                $config['path'], $config['domain'], $config['secure'], false
            )
        );
    }
    return $response;
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!