I'm having some problems with Laravel 5.7 multi-auth implementation.
I have created a new table for backend login: "AdminUsers".
So, I modified auth.php file:
return [
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'admin' => [
'driver' => 'session',
'provider' => 'admins',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => Ecommerce\User::class,
],
'admins' => [
'driver' => 'eloquent',
'table' => Ecommerce\AdminUser::class,
],
],
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
],
'admins' => [
'provider' => 'admins',
'table' => 'password_resets',
'expire' => 60,
],
],
];
Then, I create the AdminLoginController class:
<?php
namespace Ecommerce\Http\Controllers\Admin\Auth;
use Illuminate\Http\Request;
use Ecommerce\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class AdminLoginController extends Controller
{
use AuthenticatesUsers;
protected $redirectTo = '/index';
public function __construct()
{
$this->middleware('guest')->except('logout');
}
public function showLoginForm()
{
return view('admin.auth.login');
}
protected function attemptLogin(Request $request)
{
return $this->guard('admin')->attempt(
$this->credentials($request), $request->filled('remember')
);
}
protected function authenticated(Request $request, $user)
{
dd('authenticated!');
}
public function username()
{
return 'username';
}
}
I setted this routes in routes file:
Route::get ('/login', ['uses'=>'Auth\AdminLoginController#showLoginForm'])->name('login_page');
Route::post('/login', ['uses'=>'Auth\AdminLoginController#login' ])->name('do_login' );
The problem is, that when I do login, Laravel tries to use "users" guard instead of the defined "admin" guard. So that throw a SQL error (because I have not created the "Users" table in the DB).
Even if I do var_dump($this->guard('admin')) inside AdminLoginController::attemptLogin method, the response gives me a SessionGuard object with "Ecommerce\User" instead of "Ecommerce\AdminUser" that is the one defined as "admin" in auth.php guard array.
Anyone knows where else can I look to solve this?
Thanks!
The problem lies in your auth.php providers section.
'table' => Ecommerce\AdminUser::class
'table' should be replaced with 'model'.
Related
I use JWT for API authentication in Laravel 8.
When I use auth()-> in my controller , for factory() or attemp() or anything, Laravel does not know it and says:
Undefined method 'attempt'.intelephense(1013)
I don't know what I forgot to include
my AuthController :
namespace App\Http\Controllers\Api\Admin;
use App\Models\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
class AuthController extends Controller
{
public function __construct() {
$this->middleware('auth:api', ['except' => ['login', 'register']]);
}
public function login(Request $request){
$validator = Validator::make($request->all(), [
'email' => 'required|email',
'password' => 'required|string|min:6',
]);
if ($validator->fails()) {
return response()->json($validator->errors(), 422);
}
if (! $token = auth()->attempt($validator->validated())) {
return response()->json(['error' => 'Unauthorized'], 401);
}
return $this->createNewToken($token);
}
.
.
.
.
.
and my config/auth.php file :
return [
'defaults' => [
'guard' => 'api',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'jwt',
'provider' => 'users',
'hash' => false,
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
// Following array is newly added to config
'otp-user' => [
'driver' => 'otp-based-auth-provider'
],
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
'throttle' => 60,
],
],
'password_timeout' => 10800,
];
Intelephense has some trouble dealing with some methods in Laravel. You can either ignore it, as it should work or you can call it by:
JWTAuth::attempt($validator->validated)
It should make the error go away.
I have a two table login: examinee and company. company is my default auth,
every time i try to attempt auth in examinee it keeps on using the default table which is the company.
I've seen several problems that are similar to mine but it doesn't seem to work for me or I might have overlooked something that maybe some of you might be able to see.
What am I doing wrong?
Auth.php:
'defaults' => [
'guard' => 'web',
'passwords' => 'companies',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'companies',
],
'api' => [
'driver' => 'token',
'provider' => 'companies',
],
'examinees' => [
'driver' => 'session',
'provider' => 'examinees',
],
],
'providers' => [
'companies' => [
'driver' => 'eloquent',
'model' => App\Company::class,
],
'examinees' => [
'driver' => 'eloquent',
'model' => App\Examinee::class,
],
],
'passwords' => [
'companies' => [
'provider' => 'companies',
'table' => 'password_resets',
'expire' => 60,
],
'examinees' => [
'provider' => 'examinees',
'table' => 'password_resets',
'expire' => 60,
],
],
LoginController:
public function showLoginForm()
{
return view('examinee.auth.login');
}
protected function guard()
{
return Auth::guard('examinees');
}
public function login(Request $request) {
$user = Examinee::where('email', $request->get('email'))->first();
if (Auth::attempt(['id' => $user->id, 'password' => $request->get('password')])) {
// prints data from Company table instead of Examinee...
echo "AUTH USER:<pre>";
print_r(Auth::user());
echo "</pre>";
// return redirect('/home');
}
}
Model:
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class Examinee extends Authenticatable
{
use Notifiable;
protected $table = 'examinees';
protected $fillable = ['email', 'password'];
protected $hidden = ['password', 'remember_token'];
public $timestamps = false;
}
How ive done this in the past is to add the guard to your auth
Change
Auth::attempt(['id' => $user->id, 'password' => $request->get('password')
to
Auth::guard('examinees')->attempt(['id' => $user->id, 'password' => $request->get('password')
I am trying to login from two different model using same login form. I have defined admin guard in config/Auth.php. But when I define admin guard in Foundation/AuthenticateUsers it checks the database table to validate the user but redirects back to same login form.
config/auth.php
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'admin' => [
'driver' => 'session',
'provider' => 'admins',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'admins' => [
'driver' => 'eloquent',
'model' => App\Admin::class,
],
Foundation/AuthenticatUsers
protected function guard()
{
return Auth::guard('admin');
}
public function login(Request $request)
{
$credentials = $this->credentials($request);
if (Auth::guard('web')->attempt($credentials, $request- >has('remember'))) {
return $this->sendLoginResponse($request);
}
elseif(Auth::guard('admin')->attempt($credentials, $request->has('remember')))
{
return $this->sendLoginResponse($request);
}
}
Admin guard redirects to login page because of middleware auth, i think you need to do something like this
public function __construct()
{
$this->middleware('auth:admin');
}
Read this Protecting Routes, part "Specifying A Guard"
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.
can we do a 3 table authentication in laravel 5.2 like i have role for Admin, Teacher, Student and i want authentication for these 3 tables separately
At this time i have 2 table and these are authenticated separately and working fine
this is my code for auth.php
'defaults' => [
'guard' => 'user',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'user' => [
'driver' => 'session',
'provider' => 'users'
],
'admin' => [
'driver' => 'session',
'provider' => 'admins'
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'admins' => [
'driver' => 'eloquent',
'model' => App\Admin::class,
]
],
'passwords' => [
'users' => [
'provider' => 'users',
'email' => 'auth.emails.password',
'table' => 'password_resets',
'expire' => 60,
],
'admins' => [
'provider' => 'admins',
'email' => 'admin.auth.emails.password',
'table' => 'password_resets',
'expire' => 60,
],
],
AdminController.php file is look like
class AdminController extends Controller
{
public function __construct(){
$this->middleware('admin');
}
public function index(){
// return Auth::guard('admin')->user();
return view('admin.dashboard');
}
public function Profile()
{
$adminData = Auth::guard('admin')->user();
return view ('admin.add', compact('adminData'));
}
}
HomeController.php file is here
class HomeController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Show the application dashboard.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
return view('auth.dashboard');
}
}
Route file is look like this
Route::group(['middleware' => ['web']], function(){
Route::auth();
Route::get('/home', 'HomeController#index');
});
Route::group(['middleware' => ['web']], function () {
//Login Routes...
Route::get('/admin/login','AdminAuth\AuthController#showLoginForm');
Route::post('/admin/login','AdminAuth\AuthController#login');
Route::get('/admin/logout','AdminAuth\AuthController#logout');
// Registration Routes...
Route::get('admin/register', 'AdminAuth\AuthController#showRegistrationForm');
Route::post('admin/register', 'AdminAuth\AuthController#register');
Route::get('/admin', 'AdminController#index');
Route::get('/profile', 'AdminController#Profile');
});
Now i want to add another table and do builtin authentication for this new table