Home » Php » php – Get Header Authorization key in laravel controller?

php – Get Header Authorization key in laravel controller?

Posted by: admin April 23, 2020 Leave a comment

Questions:

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

$headers = apache_request_headers();

And the $header contains 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.

$header['Authorization]

Error :

Undefined index: Authorization

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

How to&Answers:

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

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

Answer:

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:

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

Or directly from a controller:

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

Answer:

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

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

<?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