如何使用中间件将授权 access_token 发送到 Laravel 中的请求标头

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/51462739/
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-09-14 17:55:17  来源:igfitidea点击:

How to send Authorization access_token to request header in Laravel using Middleware

phplaravellaravel-5laravel-middlewarelaravel-response

提问by Gabrielle-M

I'm Bulid an API Authentication System. Everything I can check using PostmanBut I want to attach this mark portion (please see the image)that's means the header portion send from my controller or middleware with request header.

我正在构建 API 身份验证系统。我可以使用的所有内容Postman但我想附加这个标记部分(please see the image),这意味着从我的控制器或中间件发送的标头部分带有请求标头。

How Can I do this Stuff. Please see my code sample.

我怎么能做这个东西。请参阅我的代码示例。

Picture. enter image description here

图片。 在此处输入图片说明

I try this using a middleware.

我尝试使用中间件。

 public function handle($request, Closure $next)
{
    $token='Bearer '.$request->bearerToken();
    $response=$next($request);
    $response->header('Authorization',$token);

    return $response;
}

Registered middleware in Kernal.

在内核中注册中间件。

protected $middlewareGroups = [

    'Header'  =>[
        \App\Http\Middleware\HeaderMiddleware::class
    ],
];

and my routes\api.php

和我的 routes\api.php

Route::group(['middleware' => ['auth:api','Header']], function(){
Route::post('details', 'API\PassportController@details');
Route::get('test','API\PassportController@test');
});

When I use Middleware it's show this result in Postman. enter image description here

当我使用中间件时,它会在 Postman 中显示此结果。 在此处输入图片说明

回答by Marcin Nabia?ek

It's possible to add some custom headers in middleware. To add custom header to response you need to do it like this:

可以在中间件中添加一些自定义标头。要将自定义标头添加到响应中,您需要这样做:

$response = $next($request);
$response->headers->set('Authorization', 'Bearer '.$request->bearerToken());

回答by Plabon Dutta

You can do something like below:

您可以执行以下操作:

 $response = $client->request('POST', '/api/details', [
    'headers' => [
        'Authorization' => 'Bearer '.$token,
        'Accept' => 'application/json',
    ],
]);