问题
I'm using JWT token to authorize android users but when i send it it reaches as null, does the server remove the Authorization header? is there a config i need to change to allow my header to pass to the backend?
回答1:
I faced this issue in cPanel hosting, some security mod or plugins strips the Authorization data from the header, I was using Authorization Bearer
. I bypassed it by renaming Authorization
-> ApiToken
and updating few lines of code in Laravel core.
file vendor\laravel\framework\src\Illuminate\Http\Concerns\InteractsWithInput.php
method bearerToken
.
public function bearerToken()
{
$header = $this->header('Authorization', $this->header('ApiToken', ''));
if (Str::startsWith($header, 'Bearer ')) {
return Str::substr($header, 7);
}
}
Btw, editing core code is not ideal.
回答2:
Just updating for the Googlers as I was also looking for a solution and felt that modifying the core code isn't a good idea!
The solution I've got is to use middleware. In my JavaScript, I'm setting X-Authorization
headers instead of Authorization
.
I've then created an HTTP middleware class to pick up this header and set our Authorization header -
<?php
namespace App\Http\Middleware;
use Closure;
class XAuthorizationHeader
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next) {
// check if we have an X-Authorization header present
if($auth = $request->header('X-Authorization')) {
$request->headers->set('Authorization', $auth);
}
return $next($request);
}
}
Then in App\Http\Kernel.php
$middleware
array, add this middleware at the very start.
protected $middleware = [
XAuthorizationHeader::class,
Any further code will then be able to retrieve the Authorization
header as if it were actually there when you pass it as an X-Authorization
header.
回答3:
Add Authorization handling code in public/.htaccess:
# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
Ref: https://github.com/laravel/laravel/blob/master/public/.htaccess
来源:https://stackoverflow.com/questions/49626796/authorization-header-not-reaching-the-server-in-laravel-project