Auth guard driver [api] is not defined - php

I am using laravel 5.4 and using jwt auth
jwt version is jwt-auth "tymon/jwt-auth": "0.5.*"
In auth.php i have
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'jwt',
'provider' => 'users',
],
],
In Api.php i have
Route::post('/login','HomeController#authenticate');
Route::group(['prefix' => 'v2','middleware' => 'auth:api',], function () {
// Authentication Routes...
Route::get('/logout','HomeController#logout');
Route::get('/home','HomeController#home');
});
When i post email and password from postman it will return token .
when i try to acccess
http://localhost/demo/public/api/v2/home
and header i passed Authorization bearer token
I am getting following error in postman
Whoops, looks like something went wrong. (1/1)
InvalidArgumentException Auth guard driver [api] is not defined. in
AuthManager.php (line 99) at AuthManager->resolve('api') in
AuthManager.php (line 70) at AuthManager->guard('api') in
Authenticate.php (line 61) at Authenticate->authenticate(array('api'))
can any help me how to fix it
Also i checked follwing issue since its old one Sep 27, 2016
https://github.com/tymondesigns/jwt-auth/issues/860

try to set token:
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token', // here !
'provider' => 'users',
],
],

Make sure in your kernel.php file you've declared it in
protected $routeMiddleware =

Not necessarily an answer, but this is the article I have used a couple times to install and setup JWT tokens and I have had no issues.
https://medium.com/employbl/build-authentication-into-your-laravel-api-with-json-web-tokens-jwt-cd223ace8d1a
Hopefully this helps, good luck!

I solved the problem by adding this line to the providers in config\app.php
'providers' => [
...
Tymon\JWTAuth\Providers\LaravelServiceProvider::class,
]

The error may occur if the API guard does not exist. In order to solve this issue, you have to set the API guard on
root->config->auth.php [line:38]
as follows
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token', // make sure to add token on API driver
'provider' => 'users',
],
],
the request from the default register form will have following inputs
local.DEBUG: array (
'_token' => 'J0FzfW7huNaJxcUZnjYXF9g63OOiSHaH9vZSBc73', // token is required from the request
'name' => 'mygem',
'phone' => '+1 (484) 853-6668',
'email' => 'cyvu#mailinator.com',
'password' => 'Pa$$w0rd!',
'password_confirmation' => 'Pa$$w0rd!',
)

I had the same issue. I solved it by adding
"tymon/jwt-auth": "^1.0"
in the require array of composer.json, then running composer install

Related

Auth0 upon laravel 5.8 unable to authenticatean entpoint: Auth0\Login\Auth0Service::__construct() must be of the type array, null given,

I try to authenticate an endpoint using the auth0 library on an existing laravel 5.8 application (I know I need a serious upgrade but ain't got time):
$ composer require auth0/login
$ php artisan vendor:publish --tag=auth0-config
And I made the following route:
Route::prefix('/test')->middleware(['auth0.authenticate'])->group(function(){
Route::get("/hello",function(){
return response()->json([
'message' => 'Hello from a private endpoint! You need to be authenticated to see this.',
'authorized' => Auth::check(),
'user' => Auth::check() ? json_decode(json_encode((array) Auth::user(), JSON_THROW_ON_ERROR), true) : null,
], 200, [], JSON_PRETTY_PRINT);
});
});
Furthermore my auth.php is:
<?php
return [
'defaults' => [
'guard' => 'auth0',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
'auth0' => [
'driver' => 'auth0',
'provider' => 'auth0',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'auth0' => [
'driver' => 'auth0',
'repository' => \Auth0\Laravel\Auth\User\Repository::class
],
],
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
],
],
];
My settings are:
AUTH0_STRATEGY=api
# The URL of your Auth0 tenant domain
# You'll find this in your Auth0 Application's settings page.
AUTH0_DOMAIN=dev-XXXXXXX.eu.auth0.com
# Your Auth0 application's Client ID
# You'll find this in your Auth0 Application's settings page.
AUTH0_CLIENT_ID=XXXXXXXXX
# Your Auth0 Custom API identifier/audience.
# You'll find this in your Custom API's settings page.
AUTH0_AUDIENCE=https://etable.local/test/
As Api says. Then I perform the following request via curl:
curl --request POST \
--url https://dev-gv9fxa52.eu.auth0.com/oauth/token \
--header 'content-type: application/json' \
--data '{"client_id":"XXXXXXX","client_secret":"XXXXXXXX",
"audience":"https://etable.local/test/",
"grant_type":"client_credentials"}'
And I perform the following request using insomnia:
GET https://api.local/test/hello
Authorization: Bearer ^bearer from api above^
But I get the following error:
Argument 1 passed to Auth0\Login\Auth0Service::__construct() must be of the type array, null given, called in /var/www/html/api/vendor/auth0/login/src/Auth0/Login/LoginServiceProvider.php on line 68
Any ideas why Service provides it not initialised?
you can check Auth0's interactive docs and follow step by step here

How to fix following error: InvalidArgumentException: Auth guard [jwt] is not defined

I have followed following guide to make an Authentication Api, and an api which uses the authentication from the first one. I have done everything exactly the same, but i still get this error:
InvalidArgumentException: Auth guard [jwt] is not defined. in file folder/to/project/vendor/laravel/framework/src/Illuminate/Auth/AuthManager.php on line 84
The guide i have followed is: https://medium.com/swlh/build-jwt-authentication-between-multiple-api-with-laravel-fbd03352aaa3
My config/auth looks like this:
'defaults' => [
'guard' => 'api',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'jwt',
'provider' => 'users',
// 'hash' => false,
],
],
Then my app/guard/JWTGuard.php looks exactly like in the guide.
My routes/api.php look the following:
Route::middleware('auth:jwt')->resource('projects', ProjectController::class);
Does anybody has this issue before and know how to solve it?
The problem was in routes/api.php. The middleware shouldn't be "auth:jwt", but "auth:api". This did the trick for me.

Auth guard [:api] is not defined?

when I use auth api gaurd for logout route. I am facing with the following Exception
Auth guard [:api] is not defined
I have already implemented registration login Apis but I am facing this error with logout api which I had protected using auth::api
config.auth file
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'passport',
'provider' => 'users',
],
],
api.php
Route::group(['prefix'=>'auth'],function(){
Route::post('login','AuthController#login');
Route::post('signup','AuthController#signup');
Route::group(['middleware' => 'auth::api'], function () {
Route::get('logout','AuthController#logout');
Route::get('user','AuthController#user');
});
});
I should be able to logout the user
If you are using Laravel 9+ and Passport, you need to implemented this inside the guard array on config/auth.php file:
'guards' => [
...
// you need to implement this
'api' => [
'driver' => 'passport',
'provider' => 'users',
'hash' => true,
],
],
You have an extra colon in your code, that's why it is trying to find the guard :api.
According to the docs:
Middleware parameters may be specified when defining the route by
separating the middleware name and parameters with a :. Multiple
parameters should be delimited by commas:
Route::put('post/{id}', function ($id) {
//
})->middleware('role:editor');
So in your case it would be:
Route::group(['prefix' => 'auth'], function () {
Route::post('login','AuthController#login');
Route::post('signup','AuthController#signup');
Route::group(['middleware' => 'auth:api'], function () {
Route::get('logout','AuthController#logout');
Route::get('user','AuthController#user');
});
});
I had the same issue, it seems that i forgot to change Authentication Defaults
so in config/auth.php change this
'defaults' => [
'guard' => 'web',
....
],
into this
'defaults' => [
'guard' => 'api',
....
],

How can I specify a guard in middleware for route?

I have two routes as follow:
Route::GET('admins/', 'UserController#index')->middleware('jwt.auth');
Route::GET('visitors', 'UserController#indexVisitors')->middleware('jwt.auth');
And I have guards in auth.php:
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'jwt-auth',
'provider' => 'users',
],
'visitor_api' => [
'driver' => 'jwt-auth',
'provider' => 'visitors',
],
],
I tried to specify the guard in the middleware but it doesn't work.
Route::GET('visitors', 'UserController#indexVisitors')
->middleware('jwt.auth.visitors_api');
If you would like to set a default guard through out the Route::group then you can use below syntax
Route::group(['middleware' => ['web','auth:visitor_api'], 'prefix' => 'visitor'], function() {
Route::get('/home', 'VisitorController#index')->name('home');
Route::get('/list', 'VisitorController#list')->name('list');
});
after this you can use Auth::id() instead of Auth::guard('visitor_api')->id() in your VisitorController.
I think this is what you want
Route::GET('visitors', 'UserController#indexVisitors')->middleware('auth:visitors_api');
You can specify a guard by passing it as a parameter (after the colon character)
You can refer to the laravel documentation:
https://laravel.com/docs/5.6/authentication
Under Authentication Quickstart > Protecting Routes > Specifying A Guard

How to change the default table/model (User) for JWT authentication in Laravel and Dontrine?

I am working on a project that was built on Laravel 5.4.24 and integrated with Symfony component and Doctrine. I need to authenticate staffs on request from site_staffs table (SiteStaff model) and return the token.
site_staffs table has these columns: (id,site_id, code, number,..). Some columns have different names in the SiteStaff entity (id,site, code,..).
There is another table for users and I have no issue to authenticate users and return the token. (In my case, I don't need to authenticate users and I just did that for testing).
The issue is when I try to change the default settings of JWT to authenticate staffs from site_staffs table as below, I get an error message (see down the page):
config/jwt.php:
//'user' => 'App\User',
'user' => 'App\Entities\SiteStaff',
config/auth.php:
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api_token' => [
'driver' => 'api_token',
'provider' => 'users',
],
//'api' => [
//'driver' => 'jwt',
//'provider' => 'users',
//],
],
'providers' => [
'users' => [
'driver' => 'doctrine',
//'model' => App\Entities\User::class,
'model' => App\Entities\SiteStaff::class,
],
pi/SiteStaffController:
I am passing the credentials to JWT as follow:
$credentials =
[
'site' => $bpId,
'code' => $lanyard_code
];
if(! $token = JWTAuth::attempt($credentials)){
return response()->json(['error' => ['messages' =>
['Invalid credentials'] ]
], IlluminateResponse::HTTP_UNAUTHORIZED);
}else{
dd($token);
}
Here is the error I get:
Type error: Argument 1 passed to
Tymon\JWTAuth\Providers\User\EloquentUserAdapter::__construct() must be an
instance of Illuminate\Database\Eloquent\Model, instance of
App\Entities\SiteStaff given, called in /vagrant/vendor/tymon/jwt-
auth/src/Providers/JWTAuthServiceProvider.php on line 126
I tried many different ways and solutions but non of them worked for me. I appreciate if you could let me know what is wrong and what am I missing?
Your help is highly appreciated.
As per the requirement to change users table name for jwt auth in laravel need to follow two-step changes which I have tried.
I have changed successfully login/authentication table from users to a customer with following steps.
step-1: change below details for providers
config/auth.php
'providers' => [
// 'users' => [
// 'driver' => 'eloquent',
// 'model' => App\User::class,
// ],
'users' => [
'driver' => 'database',
'table' => 'customer',
],
],
step-2: change in jwt file
config/jwt.php
// here to give a model path for authentication
'user' => 'App\Models\Customer',
Reference: change users table name for jwt auth in laravel
In my scenario I have two guards, web and api:
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'jwt',
'provider' => 'managers',
'hash' => false,
]
],
So, I follow these steps described in Tymon's Jwt Library docs:
"If the newly created 'api' guard is not set as a default guard or you have defined multiple guards to handle authentication, you should specify the guard when calling auth()."
$token = auth('api')->attempt($credentials);
In my custom api auth controller I had implemented login method as below and it works:
public function login(Request $request)
{
$this->validateLogin($request);
$credentials = $this->credentials($request);
$token = auth('api')->attempt($credentials);
return $token
? ['token' => $token]
: response()->json(['error' => \Lang::get('auth.failed')], 401);
}
Please, if this answer was useful for you, please give an upvote =).

Categories