I am trying to implement jwt-auth 2.1 (https://jwt-auth.readthedocs.io/en/develop/quick-start/) in Laravel 9.
I am able to generate the token properly but when I send a request in Postman using the token, the protected route does not recognize the token and returns
"message": "Unauthenticated."
.
It seems that the "if" bellow is always false and not executed.
By the way, my primary key in my table is ID.
vendor/laravel/framework/src/illuminate/Auth/Middleware/Authenticate.php
if ($this->auth->guard($guard)->check()) {
return $this->auth->shouldUse($guard);
}
How can I solve this?
Bellow is my code.
routes/api.php
<?php
use IlluminateHttpRequest;
use IlluminateSupportFacadesRoute;
use AppHttpControllersFunerariaController;
use AppHttpControllersCartorioController;
use AppHttpControllersCemiterioController;
use AppHttpControllersInumadoController;
use AppHttpControllersSepulturaController;
use AppHttpControllersTipoGuiaController;
use AppHttpControllersTipoSepulturaController;
use AppHttpControllersSolicitacaoController;
use AppHttpControllersTipoDivergenciaController;
use AppHttpControllersTipoVitimadoController;
use AppHttpControllersTipoSolicitacaoController;
use AppHttpControllersDampagofunerariaController;
use AppHttpControllersAprovadorController;
use AppHttpControllersAuthController;
use AppHttpControllersGuiaSepultamentoController;
use AppHttpControllersUsuariofunerariaController;
use AppHttpControllersUsuariorecfController;
use AppHttpControllersFunerariaFuncionarioController;
use AppHttpControllersFunerariaVeiculoController;
use AppHttpControllersCategoriacausamorteController;
use AppHttpControllersUsuarioController;
use AppHttpControllersTipoDocController;
use AppHttpControllersPlanoController;
use AppHttpControllersPlanoItemController;
use AppHttpControllersGraficosCpntroller;
Route::post('login', [AuthController::class, 'login']);
Route::post('logout',[AuthController::class, 'logout']);
Route::post('refresh',[AuthController::class, 'refresh']);
Route::post('me',[AuthController::class, 'me']);
Route::get('verify-token', [AuthController::class, 'verifyToken']);
Route::get('/funerariaview/{id}', [FunerariaController::class, 'index']);
FunerariaController.php
<?php
namespace AppHttpControllers;
use IlluminateHttpRequest;
use IlluminateHttpResponse;
use Session;
use IlluminateSupportServiceProvider;
use IlluminateRoutingController;
use AppModelsFuneraria;
use AppHttpRequests;
use CarbonCarbon;
use DB;
use IlluminateSupportFacadesHttp;
class FunerariaController extends Controller
{
public function __construct()
{
$this->middleware('auth:api');
}
AuthController.php
<?php
namespace AppHttpControllers;
use IlluminateHttpRequest;
use IlluminateSupportFacadesAuth;
// use PHPOpenSourceSaverJWTAuthFacadesJWTAuth;
use IlluminateSupportFacadesCookie;
use AppHttpControllersController;
use AppModelsUser;
use IlluminateSupportFacadesLog;
use TymonJWTAuthFacadesJWTAuth as FacadesJWTAuth;
use TymonJWTAuthFacadesJWTAuth;
use TymonJWTAuthExceptionsJWTException;
class AuthController extends Controller
{
/**
* Create a new AuthController instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth:api', ['except' => ['login','verifyToken']]);
}
public function login()
{
Log::info('Entrou em login');
$received = request(['usuario', 'senha']);
$credentials = [
'usu_nome' => $received['usuario'],
'password' => $received['senha'],
];
Log::info('credentials:',$credentials);
if (! $token = auth()->attempt($credentials)) {
return response()->json(['error' => 'Unauthorized'], 401);
}
Log::info('Gerou token');
Log::info('token:', ['token'=>$token]);
return $this->respondWithToken($token);
}
config/auth.php
<?php
return [
/*
|--------------------------------------------------------------------------
| Authentication Defaults
|--------------------------------------------------------------------------
|
| This option controls the default authentication "guard" and password
| reset options for your application. You may change these defaults
| as required, but they're a perfect start for most applications.
|
*/
'defaults' => [
'guard' => 'api',
'passwords' => 'users',
],
/*
|--------------------------------------------------------------------------
| Authentication Guards
|--------------------------------------------------------------------------
|
| Next, you may define every authentication guard for your application.
| Of course, a great default configuration has been defined for you
| here which uses session storage and the Eloquent user provider.
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| Supported: "session"
|
*/
'guards' => [
'api' => [
'driver' => 'jwt',
'provider' => 'users',
],
],
/*
|--------------------------------------------------------------------------
| User Providers
|--------------------------------------------------------------------------
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| If you have multiple user tables or models you may configure multiple
| sources which represent each model / table. These sources may then
| be assigned to any extra authentication guards you have defined.
|
| Supported: "database", "eloquent"
|
*/
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => AppModelsUser::class,
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
/*
|--------------------------------------------------------------------------
| Resetting Passwords
|--------------------------------------------------------------------------
|
| You may specify multiple password reset configurations if you have more
| than one user table or model in the application and you want to have
| separate password reset settings based on the specific user types.
|
| The expire time is the number of minutes that each reset token will be
| considered valid. This security feature keeps tokens short-lived so
| they have less time to be guessed. You may change this as needed.
|
*/
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
'throttle' => 60,
],
],
/*
|--------------------------------------------------------------------------
| Password Confirmation Timeout
|--------------------------------------------------------------------------
|
| Here you may define the amount of seconds before a password confirmation
| times out and the user is prompted to re-enter their password via the
| confirmation screen. By default, the timeout lasts for three hours.
|
*/
'password_timeout' => 10800,
];
Kernel.php
<?php
namespace AppHttp;
use IlluminateFoundationHttpKernel 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<int, class-string|string>
*/
protected $middleware = [
// AppHttpMiddlewareTrustHosts::class,
AppHttpMiddlewareTrustProxies::class,
IlluminateHttpMiddlewareHandleCors::class,
AppHttpMiddlewarePreventRequestsDuringMaintenance::class,
IlluminateFoundationHttpMiddlewareValidatePostSize::class,
AppHttpMiddlewareTrimStrings::class,
IlluminateFoundationHttpMiddlewareConvertEmptyStringsToNull::class,
AppHttpMiddlewareCors::class,
];
/**
* The application's route middleware groups.
*
* @var array<string, array<int, class-string|string>>
*/
protected $middlewareGroups = [
'web' => [
AppHttpMiddlewareEncryptCookies::class,
IlluminateCookieMiddlewareAddQueuedCookiesToResponse::class,
IlluminateSessionMiddlewareStartSession::class,
// IlluminateSessionMiddlewareAuthenticateSession::class,
IlluminateViewMiddlewareShareErrorsFromSession::class,
//AppHttpMiddlewareVerifyCsrfToken::class,
IlluminateRoutingMiddlewareSubstituteBindings::class,
],
'api' => [
// LaravelSanctumHttpMiddlewareEnsureFrontendRequestsAreStateful::class,
'throttle:api',
IlluminateRoutingMiddlewareSubstituteBindings::class,
],
];
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* @var array<string, class-string|string>
*/
protected $routeMiddleware = [
'auth' => AppHttpMiddlewareAuthenticate::class,
'jwt.verify' => AppHttpMiddlewareJwtMiddleware::class,
'auth.api' => AppHttpMiddlewareAuthenticate::class,
'auth.basic' => IlluminateAuthMiddlewareAuthenticateWithBasicAuth::class,
'cache.headers' => IlluminateHttpMiddlewareSetCacheHeaders::class,
'can' => IlluminateAuthMiddlewareAuthorize::class,
'guest' => AppHttpMiddlewareRedirectIfAuthenticated::class,
'password.confirm' => IlluminateAuthMiddlewareRequirePassword::class,
'signed' => IlluminateRoutingMiddlewareValidateSignature::class,
'throttle' => IlluminateRoutingMiddlewareThrottleRequests::class,
'verified' => IlluminateAuthMiddlewareEnsureEmailIsVerified::class,
];
}
User.php
<?php
namespace AppModels;
use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateFoundationAuthUser as Authenticatable;
use TymonJWTAuthContractsJWTSubject;
use IlluminateNotificationsNotifiable;
class User extends Authenticatable implements JWTSubject
{
use HasFactory, Notifiable;
/**
* Especifica o nome da tabela associada a este modelo.
*
* @var string
*/
protected $table = 'USUARIO';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'usu_nome',
'usu_senha',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'usu_senha',
'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
/**
* Get the identifier that will be stored in the subject claim of the JWT.
*
* @return mixed
*/
public function getJWTIdentifier()
{
return $this->getKey();
}
/**
* Return a key value array, containing any custom claims to be added to the JWT.
*
* @return array
*/
public function getJWTCustomClaims()
{
return [];
}
/**
* Sobrescreve o método para autenticação usando 'usu_nome' ao invés de 'email'.
*
* @return string
*/
public function getAuthIdentifierName()
{
return 'usu_nome';
}
/**
* Sobrescreve o método de senha para usar 'usu_0senha'.
*
* @return string
*/
public function getAuthPassword()
{
return $this->usu_senha;
}
}
2
Answers
how you are passing the token?
you need to put bearer word before the token in Authorization header
bearer {{token}}
I find this odd:
protected $table = 'USUARIO';
Shouldn’t that be
protected $table = 'users';
?Unless you really called the users table in the DB USUARIO, which is a really bad idea and will mess up your project in the very near future in impossible to find bugs, you should really follow the Laravel guidelines and call this table ‘users’ in the DB and in the User model (as ‘users’ of course).