Jwt-auth: JWT Auth not working in Lumen 5.7

Created on 19 Feb 2019  路  8Comments  路  Source: tymondesigns/jwt-auth

Hi,
I configured it according to the documentation (https://jwt-auth.readthedocs.io/en/develop/lumen-installation/ and https://jwt-auth.readthedocs.io/en/develop/quick-start/), but when trying to login, api always returns the error 500 Internal Server Error

Your environment

| Q | A
| ----------------- | ---
| Bug? | no
| New Feature? | no
| Framework | Lumen
| Framework version | 5.7.*
| Package version | 1.0.0-rc.3
| PHP version | 7.2.15

stale

Most helpful comment

It's working for me on Lumen 5.7. Using release1.0.0-rc.3 as well.
I am not even sure I got this right, but that's my current setup anyway

bootstrap\app.php

$app->withFacades();
$app->withEloquent();
...
 $app->routeMiddleware([
     "auth" => App\Http\Middleware\Authenticate::class,
 ]);
...
$app->register(App\Providers\AppServiceProvider::class);
$app->register(App\Providers\AuthServiceProvider::class);
$app->register(Tymon\JWTAuth\Providers\LumenServiceProvider::class);

config\auth.php

"defaults" => [
    "guard"     => env("AUTH_GUARD", "api"),
    "passwords" => "users",
],

"guards" => [
    "api" => [
        "driver"   => "jwt",
        "provider" => "users"
    ],
],

"providers" => [
    "users" => [
        "driver" => "eloquent",
        "model"  => \App\Models\User::class,
    ],
],

Middleware\Authenticate.php

public function handle($request, Closure $next, $guard = null) {

    if ($this->auth->guard($guard)->guest()) {
        return response("Unauthorized.", 401);
    }
    return $next($request);
}

Models\User.php

use Illuminate\Auth\Authenticatable;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Laravel\Lumen\Auth\Authorizable;
use Tymon\JWTAuth\Contracts\JWTSubject;

class User extends BaseModel implements AuthenticatableContract, AuthorizableContract, JWTSubject
{

    use Authenticatable, Authorizable;

    ...

    public function getJWTIdentifier() {
        return $this->getKey();
    }

    public function getJWTCustomClaims() {
        return [];
    }
}

Controllers\AuthController.php

public function login(Request $request) {

    // Validate
    $this->userValidator->validateLogin($request);

    // Attempt login
    $credentials = $request->only("email", "password");

    if (!$token = Auth::attempt($credentials)) {
        throw ValidationException::withMessages(["login" => "Incorrect email or password."]);
    }

    return [
        "token" => [
            "access_token" => $token,
            "token_type"   => "Bearer",
            "expire"       => (int) Auth::guard()->factory()->getTTL()
        ]
    ];
}

routes\api.php

$router->get("user", ["middleware" => "auth:api", "uses" => "UserController@authUser"]);

That's pretty much it

All 8 comments

It's working for me on Lumen 5.7. Using release1.0.0-rc.3 as well.
I am not even sure I got this right, but that's my current setup anyway

bootstrap\app.php

$app->withFacades();
$app->withEloquent();
...
 $app->routeMiddleware([
     "auth" => App\Http\Middleware\Authenticate::class,
 ]);
...
$app->register(App\Providers\AppServiceProvider::class);
$app->register(App\Providers\AuthServiceProvider::class);
$app->register(Tymon\JWTAuth\Providers\LumenServiceProvider::class);

config\auth.php

"defaults" => [
    "guard"     => env("AUTH_GUARD", "api"),
    "passwords" => "users",
],

"guards" => [
    "api" => [
        "driver"   => "jwt",
        "provider" => "users"
    ],
],

"providers" => [
    "users" => [
        "driver" => "eloquent",
        "model"  => \App\Models\User::class,
    ],
],

Middleware\Authenticate.php

public function handle($request, Closure $next, $guard = null) {

    if ($this->auth->guard($guard)->guest()) {
        return response("Unauthorized.", 401);
    }
    return $next($request);
}

Models\User.php

use Illuminate\Auth\Authenticatable;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Laravel\Lumen\Auth\Authorizable;
use Tymon\JWTAuth\Contracts\JWTSubject;

class User extends BaseModel implements AuthenticatableContract, AuthorizableContract, JWTSubject
{

    use Authenticatable, Authorizable;

    ...

    public function getJWTIdentifier() {
        return $this->getKey();
    }

    public function getJWTCustomClaims() {
        return [];
    }
}

Controllers\AuthController.php

public function login(Request $request) {

    // Validate
    $this->userValidator->validateLogin($request);

    // Attempt login
    $credentials = $request->only("email", "password");

    if (!$token = Auth::attempt($credentials)) {
        throw ValidationException::withMessages(["login" => "Incorrect email or password."]);
    }

    return [
        "token" => [
            "access_token" => $token,
            "token_type"   => "Bearer",
            "expire"       => (int) Auth::guard()->factory()->getTTL()
        ]
    ];
}

routes\api.php

$router->get("user", ["middleware" => "auth:api", "uses" => "UserController@authUser"]);

That's pretty much it

@Metainy is there any config/auth.php in lumen ?

@buildsomethingdifferent no, you need to create the file.

im using lumen 5.8, works fine, for more guide read here: https://github.com/tymondesigns/jwt-auth/issues/1102

i made a repo, a short guide to use tymon jwt auth, jwt auth guide

It's working for me on Lumen 5.7. Using release1.0.0-rc.3 as well.
I am not even sure I got this right, but that's my current setup anyway

bootstrap\app.php

$app->withFacades();
$app->withEloquent();
...
 $app->routeMiddleware([
     "auth" => App\Http\Middleware\Authenticate::class,
 ]);
...
$app->register(App\Providers\AppServiceProvider::class);
$app->register(App\Providers\AuthServiceProvider::class);
$app->register(Tymon\JWTAuth\Providers\LumenServiceProvider::class);

config\auth.php

"defaults" => [
    "guard"     => env("AUTH_GUARD", "api"),
    "passwords" => "users",
],

"guards" => [
    "api" => [
        "driver"   => "jwt",
        "provider" => "users"
    ],
],

"providers" => [
    "users" => [
        "driver" => "eloquent",
        "model"  => \App\Models\User::class,
    ],
],

Middleware\Authenticate.php

public function handle($request, Closure $next, $guard = null) {

    if ($this->auth->guard($guard)->guest()) {
        return response("Unauthorized.", 401);
    }
    return $next($request);
}

Models\User.php

use Illuminate\Auth\Authenticatable;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Laravel\Lumen\Auth\Authorizable;
use Tymon\JWTAuth\Contracts\JWTSubject;

class User extends BaseModel implements AuthenticatableContract, AuthorizableContract, JWTSubject
{

    use Authenticatable, Authorizable;

    ...

    public function getJWTIdentifier() {
        return $this->getKey();
    }

    public function getJWTCustomClaims() {
        return [];
    }
}

Controllers\AuthController.php

public function login(Request $request) {

    // Validate
    $this->userValidator->validateLogin($request);

    // Attempt login
    $credentials = $request->only("email", "password");

    if (!$token = Auth::attempt($credentials)) {
        throw ValidationException::withMessages(["login" => "Incorrect email or password."]);
    }

    return [
        "token" => [
            "access_token" => $token,
            "token_type"   => "Bearer",
            "expire"       => (int) Auth::guard()->factory()->getTTL()
        ]
    ];
}

routes\api.php

$router->get("user", ["middleware" => "auth:api", "uses" => "UserController@authUser"]);

That's pretty much it

This found for me ! I'm using lumen 5.8. Thank you :D

How do I use it with fields "login" for email and "senha" for password? I have a legacy database and the table users use for authenticate the fields login and senha and not the default email and password. Thank's.

How do I use it with fields "login" for email and "senha" for password? I have a legacy database and the table users use for authenticate the fields login and senha and not the default email and password. Thank's.

@felipepanegalli put this in your User Model:

public function getAuthIdentifier() {  
    return $this->login;
}

public function getAuthPassword() {  
    return $this->senha;
}

_This overrides the trait Illuminate\Auth\Authenticatable methods._

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.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

marciomansur picture marciomansur  路  3Comments

aofdev picture aofdev  路  3Comments

lloy0076 picture lloy0076  路  3Comments

hfalucas picture hfalucas  路  3Comments

johncloud200 picture johncloud200  路  3Comments