I define a new guard "Admin" to have a multi Auth System User and admin in my project . when i login it is ok and i get the token to the rest of my api routes .When when I use The auth::guard('Admin')->user() i got always null
Any suggestion??
Auth.php :
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'passport',
'provider' => 'users',
],
'admin' => [
'driver' => 'session',
'provider' => 'admins',
]
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'admins' => [
'driver' => 'eloquent',
'model' => App\Admin::class,
],
Login method :
public function ALogin(Request $request){
// dd($request);
// dd($rrequest->header);
if (Auth::guard('admin')->attempt(['email' => $request->email, 'password' => $request->password], $request->get('remember'))) {
$this->connectedAdmin = Auth::guard('admin')->user();
// dd( $connectedAdmin);
$success['token'] = $this->connectedAdmin->createToken('MyApp')->accessToken;
$return = new \stdClass();
$return->token = $success['token'];
//dd(self::$connectedAdmin);
return response()->json($return, 200);
}
// dd(Auth::guard('admin')->user());
return response()->json("error", 400);
}
*/
In your route file, to specify a guard for several endpoints you coud do:
/** routes/api.php */
Route::group(['guard' => 'admin'], function () {
Route::get('/a-route', 'AController#method');
// ...
});
Related
After redirecting from LoginController Auth::guard('user')->user() returns null
public function userPostLogin(array $collection)
{
return Auth::guard('web')->attempt($collection);
}
LoginConsumer
public function userLoginAuthentication(Request $request)
{
if ($request->get('phoneNumber') != null && $request->get('password') != null) {
$login = new LoginDTO($request->get('regionCode'). ' ' .$request->get('phoneNumber'), $request->get('password'), $request->get('role'));
$mapper = new LoginMapper();
return $this->userLoginConsumer->userPostLogin((array)$mapper->objectToCollection($login));}
LoginService
public function loginAuthentication(Request $request)
{
$this->userLoginService->userLoginAuthentication($request);
return redirect()->route('user-home');
LoginController
Auth::guard('web')->user() returns the right user in each of this layers. But on redirect to route('user-home') (or to any route) the same Auth::guard('web')->user() returns null
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
'hash' => false,
],
'admin' => [
'driver' => 'session',
'provider' => 'admins'
],
'admin-api' => [
'driver' => 'token',
'provider' => 'admins'
],
'kitchen' => [
'driver' => 'session',
'provider' => 'kitchens'
],
'kitchen-api' => [
'driver' => 'token',
'provider' => 'kitchens'
]
],
'providers' => [
'users' => [
'driver' => 'jsonresponse',
'model' => CustomUser::class,
],
'admins' => [
'driver' => 'jsonresponse',
'model' => CustomUser::class,
],
'kitchens' => [
'driver' => 'jsonresponse',
'model' => CustomUser::class,
],
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
'throttle' => 60,
],
],
'password_timeout' => 10800,
auth.php
You can get the user like this after your auth process like this:
Auth::user();
And you can also check like this:
if (Auth::check()) {
$user = Auth::user();
} else {
echo "We do not have a authenticated user";
}
And you should apply the auth middleware to these routes
The problem was that I didn't return when implementing Illuminate\Contracts\Auth\UserProvider the object from
public function retrieveById($identifier)
I use laravel 6, I make multiple logins, my multi logins are running, but after logging out, I get an error like this on my welcome page
Argument 2 passed to Illuminate\Auth\SessionGuard::__construct()
must implement interface Illuminate\Contracts\Auth\UserProvider, null
given, called in
D:\xampp2\htdocs\alkit\vendor\laravel\framework\src\Illuminate\Auth\AuthManager.php
on line 125
auth.php
<?php
return [
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
// Guard
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
'admin' => [
'driver' => 'session',
'provider' => 'admin',
],
'admin-api' => [
'driver' => 'token',
'provider' => 'admin',
],
'camp' => [
'driver' => 'session',
'provider' => 'camp',
],
'camp-api' => [
'driver' => 'token',
'provider' => 'camp',
],
'user' => [
'driver' => 'session',
'provider' => 'user',
],
'user-api' => [
'driver' => 'token',
'provider' => 'user',
],
],
// Providers
'providers' => [
'user' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'admin' => [
'driver' => 'eloquent',
'model' => App\Admin::class,
],
'camp' => [
'driver' => 'eloquent',
'model' => App\Camp::class,
],
],
// Password
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
],
],
];
web.php
<?php
Route::get('/home', function () {
return view('index');
});
// hanya untuk tamu yg belum auth
Route::get('/login', 'LoginController#getLogin')->name('login')->middleware('guest');
Route::post('/login', 'LoginController#postLogin');
Route::get('/logout', 'LoginController#logout');;
Route::get('/admin', function() {
return view('admin');
})->middleware('auth:admin');
Route::get('/user', function() {
return view('user');
})->middleware('auth:user');
Route::get('/camp', function() {
return view('camp');
})->middleware('auth:camp');
LoginCobtroller.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Admin;
use App\User;
use App\Camp;
use Auth;
class LoginController extends Controller
{
public function getLogin()
{
return view('login');
}
public function postLogin(Request $request)
{
// Validate the form data
$this->validate($request, [
'email' => 'required|email',
'password' => 'required'
]);
// Attempt to log the user in
// Passwordnya pake bcrypt
if (Auth::guard('admin')->attempt(['email' => $request->email, 'password' => $request->password])) {
// if successful, then redirect to their intended location
return redirect()->intended('/admin');
} else if (Auth::guard('user')->attempt(['email' => $request->email, 'password' => $request->password])) {
return redirect()->intended('/user');
} else if (Auth::guard('camp')->attempt(['email' => $request->email, 'password' => $request->password])) {
return redirect()->intended('/camp');
}
return redirect()->route('login');
}
public function logout()
{
if (Auth::guard('admin')->check()) {
Auth::guard('admin')->logout();
} else if (Auth::guard('user')->check()) {
Auth::guard('user')->logout();
} else if (Auth::guard('camp')->check()) {
Auth::guard('camp')->logout();
}
return redirect('/home');
}
}
The provider is named wrong. You should use like this
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'admins' => [
'driver' => 'eloquent',
'model' => App\Admin::class,
],
'camps' => [
'driver' => 'eloquent',
'model' => App\Camp::class,
],
],
Change the web guards configuration to use your adjusted user provider ... by default it wants to use a provider named users which you do not have.
'web' => [
'driver' => 'session',
'provider' => 'user',
],
If you are not going to be using the web guard, you should not have it set as the default. The passwords section is an issue since the only configuration you have there is set to use the users provider, which you do not have.
Similarly: https://stackoverflow.com/a/58896116/2109233
Also:
Route::get('/login', 'LoginController#getLogin')->name('login')->middleware('guest');
Since you have not specified a guard to guest it will use the default guard which is web. So everyone who isn't logged in via the web guard can reach this route.
Having said all of that ... it is probably easier to just change the user provider to be named users and adjust your user and user-api guards to use the users provider.
I had implemented custom auth in L5.2. I had followed those same steps but, I am not able to login/signup with custom auth. Following is the setup:
in auth.php i added customers custom auth:
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
'customers' => [
'driver' => 'jwt',
'provider' => 'customers',
],
],
// Providers Section
providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'customers' => [
'driver' => 'eloquent',
'model' => App\Customer::class,
],
],
Then in routes/api.php I added following code after removing middleware from RouteServiceProvider.php
Route::group(['middleware' => 'customers'], function() {
Route::post('login', 'JwtAuth\LoginController#login'); //Had made new auth for JWT
}
When I hit this login, instead of Customer table, Auth is done from User table!!
I also tried with following code inside Controller\JwtAuth\LoginController.php :
public function login(Request $request)
{
$credentials = $request->only('email', 'password');
$customer = Auth::guard('customers')->attempt($credentials);
try {
// attempt to verify the credentials and create a token for the user
if (!$token = JWTAuth::attempt($credentials)) {
return response()->json(['error' => 'invalid_credentials'], 401);
}
} catch (JWTException $e) {
// something went wrong whilst attempting to encode the token
return response()->json(['error' => 'could_not_create_token'], 500);
}
// all good so return the token
return response()->json(compact('token'), Response::HTTP_OK);
}
This code throws error as:
Auth guard driver [customers] is not defined.
In my \App\Http\Kernel.php under protected $middlewareGroups i had added:
'api' => [
'throttle:60,1',
'bindings'
],
'customers' => [
'throttle:60:1',
'bindings'
]
Is there any change in token driver or custom driver. Or how to define custom Auth driver?
Any help/guidance would b much appreciated. Thanks in advance.
Auth Guard driver is defined in config/auth.php
Like below
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'jwt',
'provider' => 'users',
],
'customers' => [
'driver' => 'jwt',
'provider' => 'customers',
],
],
and also add in providers like
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
'customers' => [
'driver' => 'eloquent',
'model' => App\Models\Customer::class,
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
Try to clear the config cache php artisan config:clear or rebuild it php artisan config:cache
You will have to also extend your authentication by adding this to the boot() method of your app's AuthServiceProvider:
public function boot()
{
$this->registerPolicies();
Auth::extend('customers', function ($app, $name, array $config) {
return new CustomersGuard();
});
}
See the documentation for adding custom guards
I'm new in Laravel. I try to use Multiple Auth in Laravel 5.3 and my auth.php file is:
<?php
return [
*/
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
'courier' => [
'driver' => 'session',
'provider' => 'couriers',
],
'client' => [
'driver' => 'session',
'provider' => 'clients',
]
],
'providers' => [
'couriers' => [
'driver' => 'eloquent',
'model' => App\Courier::class,
],
'clients' => [
'driver' => 'eloquent',
'model' => App\Client::class,
],
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
]
],
'passwords' => [
'couriers' => [
'provider' => 'couriers',
'table' => 'password_resets',
'expire' => 60,
],
'clients' => [
'provider' => 'clients',
'table' => 'password_resets',
'expire' => 60,
],
],
];
Then, when I store Clients or Couriers in the DB, I use bcrypt for password (Bring also use the function Hash::make() for passwords). For example, my model Courier is:
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
class Courier extends Authenticatable
{
[..]
public function setPasswordAttribute($pass){
$this->attributes['password'] = bcrypt($pass);
}
[..]
}
And when update a courier, in my controller I have:
public function update(Request $request, $id) {
$fieldsCourier = $request->all();
$courier = Courier::find($id);
if( isset($fieldsCourier['password']) )
$fieldsCourier['password'] = bcrypt($fieldsCourier['password']);
if( $courier->update($fieldsCourier) )
$courier = Courier::find($id);
}
I have a method called authenticate but the method attempt always return false (invalid_credentials). Even so send valid credentials.. This is my code:
public function authenticate(Request $request) {
$credentials = $request->only('email', 'password');
try {
if ( auth()->guard('courier')->attempt($credentials) ){
$user = Auth::guard('courier')->user();
} else {
return response()->json(['error' => 'invalid_credentials'], 401);
}
} catch (JWTException $e) {
return response()->json(['error' => 'could_not_create_token'], 500);
}
return response()->json(compact('user'));
}
I not know what I'm doing wrong. Anything am I doing wrong?
you have encrypt the password twice, on your model and controller.
just remove one of them
e.g: don't use bcrypt on your controller, because you have already use bcrypt on your model.
I'm trying to login an Admin and a User with the same form, but the config/auth I just only can to set a one default
This is my config/auth
'defaults' => [
'guard' => 'web_users',
'passwords' => 'users',
],
'guards' => [
'web_users' => [
'driver' => 'session',
'provider' => 'users',
],
'web_admins' => [
'driver' => 'session',
'provider' => 'admins',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'admins' => [
'driver' => 'eloquent',
'model' => App\Admin::class,
],
],
When I log in a User with the default "web_users" I can retrieve his data with the method Auth::user(), but if I log in a Admin with the default "web_admins" can't retrieve anything.
Routes:
Route::resource('log','LogController');
Route::get('logout','LogController#logout');
Log Controller
public function store(Request $request)
{
if(Auth::guard('web_users')->attempt(['email'=>$request['email'],'password'=>$request['password']])) {
return Redirect::to('/');
}
if(Auth::guard('web_admins')->attempt(['email'=>$request['email'],'password'=>$request['password']])) {
return Redirect::to('/');
}
}
public function logout()
{
Auth::logout();
return Redirect::to('log');
}
Note: sorry for my english, I don't speak it very well
try this for Routes file
Route::group(['middleware' => 'auth:web_users,web_admin'], function () {
Route::resource('log','LogController');
Route::get('logout','LogController#logout');
});