Fetching custom Authorization header from incoming PHP request

前端 未结 5 564
春和景丽
春和景丽 2020-12-04 19:47

So I\'m trying to parse an incoming request in PHP which has the following header set:

Authorization: Custom Username

Simple question: how

相关标签:
5条回答
  • 2020-12-04 19:55

    Just use:

    $headers = apache_request_headers();
    $token = $headers['token'];
    
    0 讨论(0)
  • 2020-12-04 19:58

    For background, why Apache filters away the Authorization header: https://stackoverflow.com/a/17490827

    Solutions depending on which Apache module is used to pass the request to the application:

    mod_wsgi, mod_fcgid:

    • https://stackoverflow.com/a/30310338

    cgi:

    • https://stackoverflow.com/a/38175451

    Other hacks - massaging the headers in this question:

    • Request headers bag is missing Authorization header in Symfony 2?

    • Apache 2.4 + PHP-FPM and Authorization headers

    0 讨论(0)
  • 2020-12-04 19:59

    Add this code into your .htaccess

    RewriteEngine On
    RewriteRule .* - [e=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
    

    Pass your header like Authorization: {auth_code} and finally you get the Authorization code by using $_SERVER['HTTP_AUTHORIZATION']

    Note: The above one is for apache, if you're using the nginx you don't need to update anything. you can get the value easily in nginx like:

    if you are passing authorization key, you can get the key value by just putting the $_SERVER['HTTP_AUTHORIZATION']. just add HTTP_ as the prefix in $_SERVER for get anything like

    postman_token => HTTP_POSTMAN_TOKEN
    test_key => HTTP_TEST_KEY
    
    0 讨论(0)
  • 2020-12-04 20:03

    If you're only going to use Apache you might want to have a look at apache_request_headers().

    0 讨论(0)
  • 2020-12-04 20:03

    For token based auth:

      $token = null;
      $headers = apache_request_headers();
      if(isset($headers['Authorization'])){
        $matches = array();
        preg_match('/Token token="(.*)"/', $headers['Authorization'], $matches);
        if(isset($matches[1])){
          $token = $matches[1];
        }
      } 
    
    0 讨论(0)
提交回复
热议问题