Get Header Authorization key in laravel controller?

PhpLaravelLaravel 5Authorization

Php Problem Overview


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?

Php Solutions


Solution 1 - Php

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
}

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

Solution 2 - Php

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());
    // ...
}

Solution 3 - Php

If you use a specific package like "JWT" or "sanctum" you can use their own middleware to retrieve user information.

Also, Laravel provides many ways to get the authorization key like :

  • $request->bearerToken(); to get only token without 'Bearer' word the result will be like 44|9rJp2TWvTTpWy535S1Rq2DF0AEmYbEotwydkYCZ3.
  • $request->header('Authorization'); to get the full key like Bearer 44|9rJp2TWvTTpWy535S1Rq2DF0AEmYbEotwydkYCZ3

P.S. you can use request() shortcut instead of using $request variable

Solution 4 - Php

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

Solution 5 - Php

There is a simple way to get headers in any file or controller with $_SERVER.

print_r($_SERVER); // check your header here

then, you can simply get your header:

$AuthToken = $_SERVER['HTTP_AUTHORIZATION'];

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSunilView Question on Stackoverflow
Solution 1 - PhpSzenisView Answer on Stackoverflow
Solution 2 - PhpFootnikoView Answer on Stackoverflow
Solution 3 - PhpvipmaaView Answer on Stackoverflow
Solution 4 - PhpIvan FretesView Answer on Stackoverflow
Solution 5 - PhpVishal JView Answer on Stackoverflow