【发布时间】:2014-07-27 23:45:42
【问题描述】:
我在 Laravel BaseController 中有以下代码。我想用带有令牌的 Authorization 标头保护我所有的 api 资源。
public function __construct()
{
$this->beforeFilter('@getUserFromToken');
}
public function getUserFromToken($route, $request)
{
$accessToken = Request::header('Authorization');
if(!empty($accessToken)){
$this->currentUser = User::findByToken($accessToken);
}else{
return Request::header('Authorization'); //THE PROBLEM
return Response::json(['error'=>'Not authorized. Access token needed in Header.Authorization'], 403);
}
}
如果相关,这是我的 .htaccess。
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews
</IfModule>
RewriteEngine On
# Redirect Trailing Slashes...
RewriteRule ^(.*)/$ /$1 [L,R=301]
# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</IfModule>
因此,如果我有标记的问题行,Apache 将完美地阅读所有内容。我会收到回复,但不会收到403。但是,如果我没有该行,我将收到 403 错误以及我的自定义错误消息。为什么?显然我使用的是相同的代码$this->currentUser = User::findByToken($accessToken);,为什么离开标记的行我就能得到标题?幕后是否发生了重定向,以某种方式仅第二次设置 Authorization 标头?有没有我错过的设置让 apache 第一次拿起标头?
更新:
我想我的问题是:如果我只是return Response::json(['error'=>'Not authorized. Access token needed in Header.Authorization'], 403);,我总是会得到这个错误json。我的 $accessToken 将永远是空的。为什么?
更多更新:
看起来我不应该重用Authorization Header?我试过了:
$accessToken = Request::header('Custom-Token');
if(!empty($accessToken)){
$this->currentUser = User::findByToken($accessToken);
}else{
return Response::json(['error'=>'Not authorized. Access token needed in Header.Authorization'], 403);
}
而这一次我能够得到真正的令牌。我的问题仍然存在,为什么我可以返回“神奇”的标题并突然在 Laravel 中得到它?
这个相关问题没有回答,但给我指明了正确的方向:laravel 4: why is Request::header() not getting the specified header?
还有一件事:如果我使用 php artisan serve(它使用 php 开发服务器),Authorization 标头确实可以在没有神奇返回的情况下工作。
【问题讨论】: