从传入的 PHP 请求中获取自定义授权标头

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2902621/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 08:04:12  来源:igfitidea点击:

Fetching custom Authorization header from incoming PHP request

phphttp-headersauthorization

提问by lambshaanxy

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

所以我试图在 PHP 中解析一个传入请求,它具有以下标头集:

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_TYPEis 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.

一个简单的问题:我到底如何才能得到它?如果是Authorization: Basic,我可以从$_SERVER["PHP_AUTH_USER"]. 如果是X-Custom-Authorization: Username,我可以从$_SERVER["HTTP_X_CUSTOM_AUTHORIZATION"]. 但是这些都不是由自定义授权设置的,var_dump($_SERVER)没有显示标题(特别AUTH_TYPE是缺少),并且 PHP5 功能get_headers()仅适用于对传出请求的响应。我正在使用开箱即用的 Ubuntu 安装在 Apache 上运行 PHP 5。

回答by deepwinter

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

回答by halfdan

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

如果您只想使用 Apache,您可能需要查看apache_request_headers().

回答by karthikeyan ganesan

Add this code into your .htaccess

将此代码添加到您的 .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']

传递您的标头Authorization: {auth_code},最后您通过使用获得授权代码$_SERVER['HTTP_AUTHORIZATION']

回答by joonas.fi

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

对于背景,为什么 Apache 过滤掉Authorization标题:https: //stackoverflow.com/a/17490827

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

解决方案取决于使用哪个 Apache 模块将请求传递给应用程序:

mod_wsgi, mod_fcgid:

mod_wsgi、mod_fcgid:

cgi:

CG:

Other hacks - massaging the headers in this question:

其他黑客 - 在这个问题中按摩标题:

回答by Houssin Boulla

Juste use:

正义使用:

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