Request headers bag is missing Authorization header in Symfony 2?

前端 未结 8 1494
别那么骄傲
别那么骄傲 2020-11-29 01:30

I\'m trying to implement a custom authentication provider in Symfony 2. I\'m sending a test request using Fiddler and printing all headers server side; well, Authoriza

8条回答
  •  南方客
    南方客 (楼主)
    2020-11-29 01:35

    I had the same problem when writing a public API with custom Authorization header. To fix the HeaderBag I used a listener:

    namespace My\Project\Frontend\EventListener;
    
    use Symfony\Component\HttpFoundation\HeaderBag;
    
    use Symfony\Component\HttpKernel\Event\GetResponseEvent;
    
    /**
     * Listener for the REQUEST event. Patches the HeaderBag because the
     * "Authorization" header is not included in $_SERVER
     */
    class AuthenticationHeaderListener
    {
        /**
         * Handles REQUEST event
         *
         * @param GetResponseEvent $event the event
         */
        public function onKernelRequest(GetResponseEvent $event)
        {
            $this->fixAuthHeader($event->getRequest()->headers);
        }
        /**
         * PHP does not include HTTP_AUTHORIZATION in the $_SERVER array, so this header is missing.
         * We retrieve it from apache_request_headers()
         *
         * @param HeaderBag $headers
         */
        protected function fixAuthHeader(HeaderBag $headers)
        {
            if (!$headers->has('Authorization') && function_exists('apache_request_headers')) {
                $all = apache_request_headers();
                if (isset($all['Authorization'])) {
                    $headers->set('Authorization', $all['Authorization']);
                }
            }
        }
    }
    

    and bound it to kernel.request in the service definition:

    services:
      fix_authentication_header_listener:
        class: My\Project\Frontend\EventListener\AuthenticationHeaderListener
        tags:
          - { name: kernel.event_listener, event: kernel.request, method: onKernelRequest, priority: 255 }
    

提交回复
热议问题