php 在laravel控制器中获取标题授权密钥?

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

Get Header Authorization key in laravel controller?

phplaravellaravel-5authorization

提问by Sunil

Trying to get the header authorization keyin controller for making an API. Request is making from fiddler.

试图在控制器中获取标头授权密钥以制作API。请求是从fiddler发出的。

$headers = apache_request_headers();

And the $headercontains an array.

$头包含一个数组。

Array
(
    [User-Agent] => Fiddler
    [Host] => localhost:8000
    [Content-Length] => 102
    [Authorization] => TestKey
)

If am trying like this to fetch the Authorization, its throwing error.

如果我像这样尝试获取Authorization,则会抛出错误。

$header['Authorization]

Error:

错误

Undefined index: Authorization

Tried many ways to get the authorization, but not working anything. Is there any way to fetch this?

尝试了很多方法来获得授权,但没有任何效果。有没有办法获取这个?

回答by Szenis

To get headers from the request you should use the Request class

要从请求中获取标头,您应该使用 Request 类

public function yourControllerFunction(\Illuminate\Http\Request $request)
{
    $header = $request->header('Authorization');

    // do some stuff
}

https://laravel.com/api/5.0/Illuminate/Http/Request.html#method_header

https://laravel.com/api/5.0/Illuminate/Http/Request.html#method_header

回答by Footniko

Though it's an old topic, it might be useful for somebody...
In new Laravel versions, it's possible to get bearer Authorization token directly by calling Illuminate\Http\Request's bearerToken()method:

虽然是个老话题,但对
某些人来说可能有用……在新的 Laravel 版本中,可以通过调用Illuminate\Http\RequestbearerToken()方法直接获取承载授权令牌:

Auth::viaRequest('costom-token', function (Request $request) {
    $token = $request->bearerToken();
    // ...
});

Or directly from a controller:

或者直接从控制器:

public function index(Request $request) {
    Log::info($request->bearerToken());
    // ...
}

回答by Ivan Fretes

You can try install the jwt(JSON Web Token Authentication for Laravel & Lumen) http://jwt-auth.comvia composer.

您可以尝试通过 composer安装 jwt(Laravel 和 Lumen 的 JSON Web 令牌身份验证)http://jwt-auth.com

And create a middleware that verify if exists yours token key in the header request.

并创建一个中间件来验证标头请求中是否存在您的令牌密钥。

After to install jwt, Your middleware it could be as follows

安装jwt后,你的中间件可能如下

<?php

namespace App\Http\Middleware;

use Closure;
use JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;

class VerifyJWTToken
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        try {
            $user = JWTAuth::toUser($request->header('token'));

        } catch (JWTException $e) {
            if ($e instanceof TokenExpiredException) {
                return response()->json([
                    'error' => 'token_expired',
                    'code' => $e->getStatusCode()
                ], $e->getStatusCode());
            } 
            else if($e instanceof TokenInvalidException){
                return response()->json([
                    'error' => "token_invalid",
                    'code' => $e->getStatusCode()
                ], $e->getStatusCode());
            } 
            else {
                return response()->json([
                    'error' => 'Token is required',
                    'code' => $e->getStatusCode(),

                ], $e->getStatusCode());
            }
        }

        return $next($request);
    }
}

I used token for example for a header key, but you can name it, as you like.

例如,我使用令牌作为标头键,但您可以随意命名。

Then you could use this on any controller

然后你可以在任何控制器上使用它