tymondesigns / jwt-auth

🔐 JSON Web Token Authentication for Laravel & Lumen
https://jwt-auth.com
MIT License
11.28k stars 1.55k forks source link

Headers reporting 401 on local apache machine but not live #1006

Open kyoukhana opened 7 years ago

kyoukhana commented 7 years ago

So on my local machine I have all the proper header response information returning. I am using Apache on the local machine. On the live machine is Nginx. With the live machine if the token is not valid it will return a 500 server error. Here is all of my code.

I am using Laravel 5.3. and "tymon/jwt-auth": "0.5.*"

Sample Route that requires auth

/*Track User */
    Route::get('user/track/{track}',[
        'middleware' => [
            'jwt.auth'
        ],
        'uses' => 'TracksController@getTrack'
    ]);

I access the route like this

/api/user/track/1/?token=yJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjEsImlzcyI6Imh0dHA6XC9cL3d3dy5kZXZxaS5jb21cL2FwaVwvYXV0aCIsImlhdCI6MTQ4Njk5OTE3NSwiZXhwIjoxNDg3MDAyNzc1LCJuYmYiOjE0ODY5OTkxNzUsImp0aSI6IjU0OGQ5NDgxMzQ5NzAzZWE5YzQ5MmY2MDI4OTA5NGIwIn0.7laljlbpNO3fHBNs4N3Bt2cBav6UYCp38jl1Zp5lL2k

Handler.php

<?php

namespace App\Exceptions;

use Exception;
use Illuminate\Validation\ValidationException;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that should not be reported.
     *
     * @var array
     */
    protected $dontReport = [
        AuthorizationException::class,
        HttpException::class,
        ModelNotFoundException::class,
        ValidationException::class,
    ];

    /**
     * Report or log an exception.
     *
     * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
     *
     * @param  \Exception  $e
     * @return void
     */
    public function report(Exception $e)
    {
        parent::report($e);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Exception  $exception
     * @return \Illuminate\Http\Response
     */

    public function render($request, Exception $e)
    {
        if ($e instanceof HttpResponseException) {
            return $e->getResponse();
        }

        $class = get_class($e);

        switch($class) {
            case 'Illuminate\\Http\\Exception\\HttpResponseException':
                return parent::render($request, $e);
                break;
            case 'Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException':
                $code = 'NotFound';
                $msg = 'Not Found.';
                $statusCode = 404;
                break;
            case 'Illuminate\Database\Eloquent\ModelNotFoundException':
                $code = 'ModelNotFound';
                $model = str_replace('App\\Models\\', '', $e->getModel());
                $msg = $model . ' not found.';
                $statusCode = 404;
                break;
            case 'Illuminate\Auth\Access\AuthorizationException':
                $code = 'InvalidCredentials';
                $msg = 'Credentials are invalid.';
                $statusCode = 400;
                break;
            case 'Tymon\JWTAuth\Exceptions\JWTException';
                $code = 'JWTException';
                $msg = 'There was an issue generating jwt tokens.';
                $statusCode = 400;
                break;
            case 'App\Exceptions\JWTAbsentException';
                $code = 'TokenAbsent';
                $msg = 'The token is absent.';
                $statusCode = 400;
                break;
            case 'App\Exceptions\JWTExpiredException';
                $code = 'InvalidToken';
                $msg = 'The token has expired.';
                $statusCode = 401;
                break;
            case 'App\Exceptions\JWTInvalidException';
                $code = 'InvalidToken';
                $msg = 'The token is invalid.';
                $statusCode = 401;
                break;
            case 'App\Exceptions\JWTUserNotFoundException';
                $code = 'UserNotFound';
                $msg = 'The user token does not match.';
                $statusCode = 404;
                break;
            default:
                $code = 'SystemError';
                $msg = $e->getMessage();
                $file = $e->getFile();
                $line = $e->getLine();
                $statusCode = 500;
        }

        $data = [
            'status' => 'error',
            'exception' => $class,
            'code' => $code,
            'msg' =>  $msg
        ];

        if (isset($file)) {
            $data['file'] = $file;
        }

        if (isset($line)) {
            $data['line'] = $line;
        }

        return response($data, $statusCode)
            ->header('Access-Control-Allow-Origin', '*')
            ->header('Access-Control-Allow-Headers', 'Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With')
            ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
    }

}

Kernal.php

<?php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
    ];

    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],

        'api' => [
            'throttle:60,1',
            'bindings',

        ],
    ];

    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,

        /*
       * Third Party Middleware
       */

        'jwt.auth' => \Tymon\JWTAuth\Middleware\GetUserFromToken::class,
        'jwt.refresh' => \Tymon\JWTAuth\Middleware\RefreshToken::class,
        'roles'         => 'App\Http\Middleware\CheckRole',

    ];

}

The server throws the following in the error log

2017/02/15 11:58:17 [error] 28408#28408: *14511 FastCGI sent in stderr: "PHP message: PHP Fatal error:  Uncaught Unexpecte$
Stack trace:
#0 /home/forge/restorechi.com/bootstrap/cache/compiled.php(14101): Monolog\Handler\StreamHandler->write(Array)
#1 /home/forge/restorechi.com/bootstrap/cache/compiled.php(13861): Monolog\Handler\AbstractProcessingHandler->handle(Array)
#2 /home/forge/restorechi.com/bootstrap/cache/compiled.php(13959): Monolog\Logger->addRecord(400, Object(UnexpectedValueEx$
#3 /home/forge/restorechi.com/bootstrap/cache/compiled.php(13654): Monolog\Logger->error(Object(UnexpectedValueException),$
#4 /home/forge/restorechi.com/bootstrap/cache/compiled.php(13625): Illuminate\Log\Writer->writeLog('error', Object(Unexpec$
#5 /home/forge/restorechi.com/vendor/laravel/framework/src/Illuminate/Foundation/Excepti...
PHP message: PHP Fatal error:  Uncaught UnexpectedValueException: The stream or file "/home/forge/restorechi.com/storage/l$
Stack trace:
#0 /home/forge/restorechi.com/bootstrap/cache/compiled.php(14101): Monolog\Handler\StreamHandler->write(Array)
#1 /home/forge/restorechi.com/bootstrap/cache/compiled.php(13861): Monolog\Handler\AbstractProcessingHandler->handle(Array)
#2 /home/forge/restorechi.com/bootstrap/cache/compiled.php(13959): Monolog\Logger->addRecord(400, Object(Symfony\Component$
#3 /home/forge/restorechi.com/bootstrap/cache/compiled.php(13654): Monolog\Logger->error(Object(Symfony\Component\Debug\Ex$
#4 /home/forge/restorechi.com/bootstrap/cache/compiled.php(13625): Illuminate\Log\Writer->writeLog('error', O
2017/02/15 12:03:28 [error] 28408#28408: *14514 FastCGI sent in stderr: "PHP message: PHP Fatal error:  Uncaught Unexpecte$
Stack trace:
ganchuhang commented 5 years ago

@kyoukhana how do you solve this in the end?

stale[bot] commented 3 years ago

Is this still relevant? If so, what is blocking it? Is there anything you can do to help move it forward?

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs.