Fetching custom Authorization header from incoming PHP request

北战南征 提交于 2019-12-03 18:32:31

问题


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

Authorization: Custom Username

Simple question: how on earth do I get my hands on it? If it was Authorization: Basic, I could get the username from $_SERVER["PHP_AUTH_USER"]. If it was X-Custom-Authorization: Username, I could get the username from $_SERVER["HTTP_X_CUSTOM_AUTHORIZATION"]. But neither of these are set by a custom Authorization, var_dump($_SERVER) reveals no mention of the header (in particular, AUTH_TYPE is missing), and PHP5 functions like get_headers() only work on responses to outgoing requests. I'm running PHP 5 on Apache with an out-of-the box Ubuntu install.


回答1:


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




回答2:


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];
    }
  } 



回答3:


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']




回答4:


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




回答5:


Juste use:

$headers = apache_request_headers();
$token = $headers['token'];


来源:https://stackoverflow.com/questions/2902621/fetching-custom-authorization-header-from-incoming-php-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!