Laravel Jwt auth attempts returns false always - laravel

Hope you are doing well. ;)
However, I m facing problems while generating JWT Auth Token
we have a custom user table called somename_users where email field called email_id and we used md5 hash to store the password (don't judge). So first I tried to do some tests and it worked, I was successfully generated JWT auth token, so after that, I'm trying to implement it on our dev server.
App\Model\User.php
<?php
namespace App\Model;
use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable implements JWTSubject
{
use Notifiable;
const CREATED_AT = 'created_at';
const UPDATED_AT = 'modified_at';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'first_name','middle_name','last_name','email_id','password',[...]
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password'
];
/**
* 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 [];
}
}
App\Http\Controllers\api\v1\TestController.php*
namespace App\Http\Controllers\api\v1;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use JWTAuth;
use App\Model\User;
class TestController extends Controller
{
// public function get(){
// return User::all();
// }
// public function login(Request $request)
// {
// $creds = array();
// $creds["email_id"] = $request->email_id;
// $creds["password"] = md5($request->password);
// try {
// if (! $token = JWTAuth::attempt($creds)) {
// return response()->json(['error' => 'invalid_credentials','token'=>$token], 400);
// }
// } catch (JWTException $e) {
// return response()->json(['error' => 'could_not_create_token'], 500);
// }
// return response()->json(compact('token'));
// }
// /**
// * Get the token array structure.
// *
// * #param string $token
// *
// * #return \Illuminate\Http\JsonResponse
// */
// protected function respondWithToken($token)
// {
// return response()->json([
// 'access_token' => $token,
// 'token_type' => 'bearer',
// 'expires_in' => auth()->factory()->getTTL()
// ]);
// }
/**
* Create a new AuthController instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth:api', ['except' => ['login']]);
}
/**
* Get a JWT via given credentials.
*
* #return \Illuminate\Http\JsonResponse
*/
public function login(Request $request)
{
$creds = array();
$creds["email_id"] = $request->email_id;
$creds["password"] = md5($request->password);
$creds = array();
$creds["email_id"] = $request->email_id;
$creds["password"] = md5($request->password);
if (! $token = auth()->attempt($creds)) {
return response()->json(['error' => 'Unauthorized'], 401);
}
return $this->respondWithToken($token);
}
/**
* Get the authenticated User.
*
* #return \Illuminate\Http\JsonResponse
*/
public function me()
{
return response()->json(auth()->user());
}
/**
* Log the user out (Invalidate the token).
*
* #return \Illuminate\Http\JsonResponse
*/
public function logout()
{
auth()->logout();
return response()->json(['message' => 'Successfully logged out']);
}
/**
* Refresh a token.
*
* #return \Illuminate\Http\JsonResponse
*/
public function refresh()
{
return $this->respondWithToken(auth()->refresh());
}
/**
* Get the token array structure.
*
* #param string $token
*
* #return \Illuminate\Http\JsonResponse
*/
protected function respondWithToken($token)
{
return response()->json([
'access_token' => $token,
'token_type' => 'bearer',
'expires_in' => auth()->factory()->getTTL() * 60
]);
}
}
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", "token"
|
*/
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'jwt',
'provider' => 'users',
'hash' => false,
],
],
/*
|--------------------------------------------------------------------------
| 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' => [
//original
'users' => [
'driver' => 'eloquent',
'model' => App\Model\User::class,
//'table' => 'users',
],
// 'users' => [
// 'driver' => 'eloquent',
// 'model' => App\Model\User::class,
// ],
/*'users' => [
'driver' => 'eloquent',
'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 the reset token should 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' => [
//original
/*'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
'throttle' => 60,
],*/
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 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,
];
Every time I try to hit the API endpoint of login with email and password I got unauthorized response, but credentials are absolutely perfect.
Please help me.
Thanks in advance

laravel login attempt for password working with bcrypt instead of md5, so your code must be changed.
TestController.php
public function __construct()
{
...
$this->guard = "api"; // add
}
public function login(Request $request)
{
$validator = Validator::make($request->all(), [
'email_id' => 'required|string',
'password' => 'required|string',
]);
if ($validator->fails()) {
return response()->json($validator->errors(), 422);
}
$user = \App\User::where([
'email_id' => $request->email_id,
'password' => md5($request->password)
])->first();
if (! $user ) return response()->json([ 'email_id' => ['Unauthorized'] ], 401);
if (! $token = auth( $this->guard )->login( $user ) ) {
return response()->json([ 'email_id' => ['Unauthorized'] ], 401);
}
return $this->respondWithToken($token);
}

Related

Laravel custom middleware returning guard as false

I am making a custom authentication in laravel 9 with custom middleware and custom guard, But the guard in my custom middleware returns false, This is my code
<?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' => 'web',
'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' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'admin' => [
'driver' => 'session',
'provider' => 'admins',
]
],
/*
|--------------------------------------------------------------------------
| 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' => App\Models\User::class,
],
'admins' => [
'driver' => 'eloquent',
'model' => App\Models\Admin::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,
];
This is my kernel
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 = [
// \App\Http\Middleware\TrustHosts::class,
\App\Http\Middleware\TrustProxies::class,
\Illuminate\Http\Middleware\HandleCors::class,
\App\Http\Middleware\PreventRequestsDuringMaintenance::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
];
/**
* The application's route middleware groups.
*
* #var array<string, array<int, class-string|string>>
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
// \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::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' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'auth.session' => \Illuminate\Session\Middleware\AuthenticateSession::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
'signed' => \App\Http\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
'admin' => \App\Http\Middleware\AdminMiddleware::class,
];
}
The middleware is registered as "admin"
This is my middleware which is returning false when i dd the guard gu
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
class AdminMiddleware
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle(Request $request, Closure $next){
dd(Auth::guard('admin')->check());
// dd('hh');
if(Auth::guard('admin')->check() ){
return $next($request);
}
return redirect()->route('admin.login');
}
}
This is my login controller
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Models\Admin;
use Illuminate\Http\Request;
use App\Providers\RouteServiceProvider;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;
// use Illuminate\Foundation\Auth\AuthenticatesUsers;
class AdminLoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
// use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* #var string
*/
// protected function authenticated()
// {
// return redirect()->route('admin.dashboard');
// }
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
// $this->middleware('guest:admin')->except('logout');
}
public function showLoginForm()
{
return view('login');
}
public function adminLogin(Request $request) {
$request->validate([
'email' => 'required|email',
'password' => 'required',
]);
$credentials = $request->only('email','password');
$remember_me = $request->has('remember') ? true : false;
if (Auth::guard('admin')->attempt($credentials, $remember_me)) {
// $user = Auth::guard('admin')->user()->id;
// $user = Admin::find($user);
// Auth::guard('admin')->login($user);
return redirect()->route('admin.dashboard');
}
// dd(Auth::guard('admin')->check());
return redirect()->route('admin.login')->with('error', 'Email or Password is incorrect!');
}
}
And lastly this is my route service provider where i have added the route in the middleware
<?php
namespace App\Providers;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Facades\Route;
class RouteServiceProvider extends ServiceProvider
{
/**
* The path to the "home" route for your application.
*
* Typically, users are redirected here after authentication.
*
* #var string
*/
public const HOME = '/home';
/**
* Define your route model bindings, pattern filters, and other route configuration.
*
* #return void
*/
public function boot()
{
$this->configureRateLimiting();
$this->routes(function () {
Route::middleware('api')
->prefix('api')
->group(base_path('routes/api.php'));
Route::middleware('web')
->group(base_path('routes/web.php'));
Route::middleware('admin')
->prefix('admin')
->namespace($this->namespace)
->group(base_path('routes/admin.php'));
});
}
/**
* Configure the rate limiters for the application.
*
* #return void
*/
protected function configureRateLimiting()
{
RateLimiter::for('api', function (Request $request) {
return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());
});
}
}
I have tried everything, This is the exact same thing i am using in one of my other projects and it's working which is on laravel 7, But this version is laravel 9 and it's not working here, I have checked the docs, I did not find anything which could relate to this,
Thanks
in your AdminMiddleware can you try using auth('admin')->check(); instead of Auth::guard('admin')->check();

Under no circumstances do Politic methods work in laravel 8

When calling a method:
$this->authorize('view', Role::class);
In the controller:
<?php
namespace App\Modules\Admin\Role\Controllers;
use App\Modules\Admin\Dashboard\Classes\Base;
use App\Modules\Admin\Role\Models\Role;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class RoleController extends Base
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$this->authorize('view', Role::class);
$roles = Role::all();
$this->title = "Title Role Index";
$this->content = view('Admin::Role.index')->
with([
'roles' => $roles,
'title' => $this->title,
])->render();
return $this->renderOutput();
}
/**
* Create of the resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
}
/**
* Display the specified resource.
*
* #param \App\Modules\Admin\Role\Models\Role $role
* #return \Illuminate\Http\Response
*/
public function show(Role $role)
{
//
}
/**
* Display the specified resource.
*
* #param \App\Modules\Admin\Role\Models\Role $role
* #return \Illuminate\Http\Response
*/
public function edit(Role $role)
{
//
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\Modules\Admin\Role\Models\Role $role
* #return \Illuminate\Http\Response
*/
public function update(Request $request, Role $role)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param \App\Modules\Admin\Role\Models\Role $role
* #return \Illuminate\Http\Response
*/
public function destroy(Role $role)
{
//
}
}
Always get from browser:
403 | This action is unauthorized.
My Routes:
<?php
Route::group(['prefix' => 'roles', 'middleware' => []], function () {
Route::get('/', 'RoleController#index')->name('roles.index');
Route::get('/create', 'RoleController#create')->name('roles.create');
Route::post('/', 'RoleController#store')->name('roles.store');
Route::get('/{role}', 'RoleController#show')->name('roles.read');
Route::get('/edit/{role}', 'RoleController#edit')->name('roles.edit');
Route::put('/{role}', 'RoleController#update')->name('roles.update');
Route::delete('/{role}', 'RoleController#destroy')->name('roles.delete');
});
Route::group(['prefix' => 'permissions', 'middleware' => []], function () {
Route::get('/', 'PermissionsController#index')->name('permissions.index');
Route::get('/create', 'PermissionsController#create')->name('permissions.create');
Route::post('/', 'PermissionsController#store')->name('permissions.store');
Route::get('/{role}', 'PermissionsController#show')->name('permissions.read');
Route::get('/edit/{role}', 'PermissionsController#edit')->name('permissions.edit');
Route::put('/{role}', 'PermissionsController#update')->name('permissions.update');
Route::delete('/{role}', 'PermissionsController#destroy')->name('permissions.delete');
});
Politic:
<?php
namespace App\Modules\Admin\Role\Policies;
use App\Modules\Admin\Role\Models\Role;
use App\Modules\Admin\Users\Models\User;
use Illuminate\Auth\Access\HandlesAuthorization;
class RolePolicy
{
use HandlesAuthorization;
public function view(): bool {
// never run
return true;
}
public function create(): bool {
// never run
return true;
}
public function update(): bool {
// never run
return true;
}
public function delete(): bool {
// never run
return true;
}
public function viewAny(): bool {
// never run
return true;
}
public function before() {
// never run
return true;
}
}
File AuthServiceProvider:
<?php
namespace App\Providers;
use App\Modules\Admin\Role\Models\Role;
use App\Modules\Admin\Role\Policies\Role2Policy;
use App\Modules\Admin\Role\Policies\RolePolicy;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Gate;
class AuthServiceProvider extends ServiceProvider
{
/**
* The policy mappings for the application.
*
* #var array
*/
protected $policies = [
Role::class => RolePolicy::class,
// Role::class => Role2Policy::class,
];
/**
* Register any authentication / authorization services.
*
* #return void
*/
public function boot()
{
$this->registerPolicies();
//
}
}
File 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' => 'web',
'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' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'passport',
'provider' => 'users',
'hash'=>false,
],
],
/*
|--------------------------------------------------------------------------
| 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' => \App\Modules\Admin\Users\Models\User::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 the reset token should 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,
];
File config/app.php:
<?php
use Facades\Menu;
return [
/*
|--------------------------------------------------------------------------
| Application Name
|--------------------------------------------------------------------------
|
| This value is the name of your application. This value is used when the
| framework needs to place the application's name in a notification or
| any other location as required by the application or its packages.
|
*/
'name' => env('APP_NAME', 'Laravel'),
/*
|--------------------------------------------------------------------------
| Application Environment
|--------------------------------------------------------------------------
|
| This value determines the "environment" your application is currently
| running in. This may determine how you prefer to configure various
| services the application utilizes. Set this in your ".env" file.
|
*/
'env' => env('APP_ENV', 'production'),
/*
|--------------------------------------------------------------------------
| Application Debug Mode
|--------------------------------------------------------------------------
|
| When your application is in debug mode, detailed error messages with
| stack traces will be shown on every error that occurs within your
| application. If disabled, a simple generic error page is shown.
|
*/
'debug' => (bool) env('APP_DEBUG', false),
/*
|--------------------------------------------------------------------------
| Application URL
|--------------------------------------------------------------------------
|
| This URL is used by the console to properly generate URLs when using
| the Artisan command line tool. You should set this to the root of
| your application so that it is used when running Artisan tasks.
|
*/
'url' => env('APP_URL', 'http://localhost'),
'asset_url' => env('ASSET_URL', null),
/*
|--------------------------------------------------------------------------
| Application Timezone
|--------------------------------------------------------------------------
|
| Here you may specify the default timezone for your application, which
| will be used by the PHP date and date-time functions. We have gone
| ahead and set this to a sensible default for you out of the box.
|
*/
'timezone' => 'UTC',
/*
|--------------------------------------------------------------------------
| Application Locale Configuration
|--------------------------------------------------------------------------
|
| The application locale determines the default locale that will be used
| by the translation service provider. You are free to set this value
| to any of the locales which will be supported by the application.
|
*/
'locale' => 'ru',
'locales' => ['ru', 'en'],
/*
|--------------------------------------------------------------------------
| Application Fallback Locale
|--------------------------------------------------------------------------
|
| The fallback locale determines the locale to use when the current one
| is not available. You may change the value to correspond to any of
| the language folders that are provided through your application.
|
*/
'fallback_locale' => 'en',
/*
|--------------------------------------------------------------------------
| Faker Locale
|--------------------------------------------------------------------------
|
| This locale will be used by the Faker PHP library when generating fake
| data for your database seeds. For example, this will be used to get
| localized telephone numbers, street address information and more.
|
*/
'faker_locale' => 'en_US',
/*
|--------------------------------------------------------------------------
| Encryption Key
|--------------------------------------------------------------------------
|
| This key is used by the Illuminate encrypter service and should be set
| to a random, 32 character string, otherwise these encrypted strings
| will not be safe. Please do this before deploying an application!
|
*/
'key' => env('APP_KEY'),
'cipher' => 'AES-256-CBC',
/*
|--------------------------------------------------------------------------
| Autoloaded Service Providers
|--------------------------------------------------------------------------
|
| The service providers listed here will be automatically loaded on the
| request to your application. Feel free to add your own services to
| this array to grant expanded functionality to your applications.
|
*/
'providers' => [
/*
* Laravel Framework Service Providers...
*/
Illuminate\Auth\AuthServiceProvider::class,
Illuminate\Broadcasting\BroadcastServiceProvider::class,
Illuminate\Bus\BusServiceProvider::class,
Illuminate\Cache\CacheServiceProvider::class,
Illuminate\Foundation\Providers\ConsoleSupportServiceProvider::class,
Illuminate\Cookie\CookieServiceProvider::class,
Illuminate\Database\DatabaseServiceProvider::class,
Illuminate\Encryption\EncryptionServiceProvider::class,
Illuminate\Filesystem\FilesystemServiceProvider::class,
Illuminate\Foundation\Providers\FoundationServiceProvider::class,
Illuminate\Hashing\HashServiceProvider::class,
Illuminate\Mail\MailServiceProvider::class,
Illuminate\Notifications\NotificationServiceProvider::class,
Illuminate\Pagination\PaginationServiceProvider::class,
Illuminate\Pipeline\PipelineServiceProvider::class,
Illuminate\Queue\QueueServiceProvider::class,
Illuminate\Redis\RedisServiceProvider::class,
Illuminate\Auth\Passwords\PasswordResetServiceProvider::class,
Illuminate\Session\SessionServiceProvider::class,
Illuminate\Translation\TranslationServiceProvider::class,
Illuminate\Validation\ValidationServiceProvider::class,
Illuminate\View\ViewServiceProvider::class,
Lavary\Menu\ServiceProvider::class,
/*
* Package Service Providers...
*/
/*
* Application Service Providers...
*/
App\Providers\AppServiceProvider::class,
App\Providers\AuthServiceProvider::class,
// App\Providers\BroadcastServiceProvider::class,
App\Providers\EventServiceProvider::class,
App\Providers\RouteServiceProvider::class,
App\Services\Localization\LocalizationServiceProvider::class,
App\Providers\ModularProvider::class,
/*
* modular provider
*/
],
/*
|--------------------------------------------------------------------------
| Class Aliases
|--------------------------------------------------------------------------
|
| This array of class aliases will be registered when this application
| is started. However, feel free to register as many as you wish as
| the aliases are "lazy" loaded so they don't hinder performance.
|
*/
'aliases' => [
'App' => Illuminate\Support\Facades\App::class,
'Arr' => Illuminate\Support\Arr::class,
'Artisan' => Illuminate\Support\Facades\Artisan::class,
'Auth' => Illuminate\Support\Facades\Auth::class,
'Blade' => Illuminate\Support\Facades\Blade::class,
'Broadcast' => Illuminate\Support\Facades\Broadcast::class,
'Bus' => Illuminate\Support\Facades\Bus::class,
'Cache' => Illuminate\Support\Facades\Cache::class,
'Config' => Illuminate\Support\Facades\Config::class,
'Cookie' => Illuminate\Support\Facades\Cookie::class,
'Crypt' => Illuminate\Support\Facades\Crypt::class,
'Date' => Illuminate\Support\Facades\Date::class,
'DB' => Illuminate\Support\Facades\DB::class,
'Eloquent' => Illuminate\Database\Eloquent\Model::class,
'Event' => Illuminate\Support\Facades\Event::class,
'File' => Illuminate\Support\Facades\File::class,
'Gate' => Illuminate\Support\Facades\Gate::class,
'Hash' => Illuminate\Support\Facades\Hash::class,
'Http' => Illuminate\Support\Facades\Http::class,
'Js' => Illuminate\Support\Js::class,
'Lang' => Illuminate\Support\Facades\Lang::class,
'Log' => Illuminate\Support\Facades\Log::class,
'Mail' => Illuminate\Support\Facades\Mail::class,
'Notification' => Illuminate\Support\Facades\Notification::class,
'Password' => Illuminate\Support\Facades\Password::class,
'Queue' => Illuminate\Support\Facades\Queue::class,
'RateLimiter' => Illuminate\Support\Facades\RateLimiter::class,
'Redirect' => Illuminate\Support\Facades\Redirect::class,
// 'Redis' => Illuminate\Support\Facades\Redis::class,
'Request' => Illuminate\Support\Facades\Request::class,
'Response' => Illuminate\Support\Facades\Response::class,
'Route' => Illuminate\Support\Facades\Route::class,
'Schema' => Illuminate\Support\Facades\Schema::class,
'Session' => Illuminate\Support\Facades\Session::class,
'Storage' => Illuminate\Support\Facades\Storage::class,
'Str' => Illuminate\Support\Str::class,
'URL' => Illuminate\Support\Facades\URL::class,
'Validator' => Illuminate\Support\Facades\Validator::class,
'View' => Illuminate\Support\Facades\View::class,
'Menu' => Lavary\Menu\Facade::class,
],
];
File .env:
APP_NAME=Laravel
APP_ENV=local
APP_KEY=base64:2R0mEOI/CEYoRmqtxg9c/FUu1RJIXGU9hIUVFL21fYA=
APP_DEBUG=true
APP_URL=http://crm.loc.test
LOG_CHANNEL=stack
LOG_DEPRECATIONS_CHANNEL=null
LOG_LEVEL=debug
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=crm
DB_USERNAME=root
DB_PASSWORD=
BROADCAST_DRIVER=log
CACHE_DRIVER=file
FILESYSTEM_DRIVER=local
QUEUE_CONNECTION=sync
SESSION_DRIVER=file
SESSION_LIFETIME=120
MEMCACHED_HOST=127.0.0.1
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
MAIL_MAILER=smtp
MAIL_HOST=mailhog
MAIL_PORT=1025
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS=null
MAIL_FROM_NAME="${APP_NAME}"
AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=
AWS_USE_PATH_STYLE_ENDPOINT=false
PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_APP_CLUSTER=mt1
MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"
File Models Role:
<?php
namespace App\Modules\Admin\Role\Models;
use App\Modules\Admin\Users\Models\User;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Role extends Model
{
use HasFactory;
protected $fillable = [
'alias',
'title',
];
/**
* #return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function users() {
return $this->belongsToMany(User::class);
}
/**
* #return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function perms() {
return $this->belongsToMany(Permission::class);
}
public function savePermissions($perms) {
if(!empty($perms)) {
$this->perms()->sync($perms);
}
else {
$this->perms()->detach();
}
}
}
Please help me solve the problem. I am new to laravel.
Add use AuthorizesRequests; to your code
<?php
namespace App\Modules\Admin\Role\Controllers;
use App\Modules\Admin\Dashboard\Classes\Base;
use App\Modules\Admin\Role\Models\Role;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests; // add this
class RoleController extends Base
{
use AuthorizesRequests; // add this
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$this->authorize('view', Role::class);
$roles = Role::all();
$this->title = "Title Role Index";
$this->content = view('Admin::Role.index')->
with([
'roles' => $roles,
'title' => $this->title,
])->render();
return $this->renderOutput();
}
/**
* Create of the resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
}
/**
* Display the specified resource.
*
* #param \App\Modules\Admin\Role\Models\Role $role
* #return \Illuminate\Http\Response
*/
public function show(Role $role)
{
//
}
/**
* Display the specified resource.
*
* #param \App\Modules\Admin\Role\Models\Role $role
* #return \Illuminate\Http\Response
*/
public function edit(Role $role)
{
//
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\Modules\Admin\Role\Models\Role $role
* #return \Illuminate\Http\Response
*/
public function update(Request $request, Role $role)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param \App\Modules\Admin\Role\Models\Role $role
* #return \Illuminate\Http\Response
*/
public function destroy(Role $role)
{
//
}
}

Unable to login as admin in laravel

I have used laravel default authentication by using composer require laravel/ui and I have copy the default authentication and made new table called admin so that I can login as admin I am able to register but I am unable to login
web.php
Route::get('/admin/login',[App\Http\Controllers\admin\Auth\LoginController::class,'showLoginForm'])->name('admin.login');
Route::post('/admin/login',[App\Http\Controllers\admin\Auth\LoginController::class,'login']);
Route::get('/admin/register',[App\Http\Controllers\admin\Auth\RegisterController::class,'showRegistrationForm'])->name('admin.register');
Route::post('/admin/register',[App\Http\Controllers\admin\Auth\RegisterController::class,'register'])->name('admin.register');
Logincontroller.php
<?php
namespace App\Http\Controllers\admin\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo = RouteServiceProvider::HOME;
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
public function showLoginForm()
{
return view('admin');
}
public function login(Request $request)
{
$this->validateLogin($request);
if ($this->attemptLogin($request)) {
return $this->sendLoginResponse($request);
}
return $this->sendFailedLoginResponse($request);
}
protected function sendLoginResponse(Request $request)
{
$request->session()->regenerate();
$this->clearLoginAttempts($request);
if ($response = $this->authenticated($request, $this->guard('admin'))) {
return $response;
}
// if ($response = $this->authenticated($request, $this->guard()->admin())) {
// return $response;
// }
return $request->wantsJson()
? new JsonResponse([], 204)
: redirect()->intended($this->redirectPath());
}
public function guard()
{
return Auth::guard('admin');
}
}
Registercontroller.php
<?php
namespace App\Http\Controllers\admin\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use App\Models\User;
use Illuminate\Auth\Events\Registered;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use App\Models\Admin;
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* #var string
*/
protected $redirectTo = RouteServiceProvider::HOME;
/**
* Create a new controller instance.
*
* #return void
*/
public function showRegistrationForm()
{
return view('admin-register');
}
public function register(Request $request)
{
$this->validator($request->all())->validate();
event(new Registered($user = $this->create($request->all())));
// $this->guard()->login($user);
if ($response = $this->registered($request, $user)) {
return $response;
}
return $request->wantsJson()
? new JsonResponse([], 201)
: redirect($this->redirectPath());
}
public function __construct()
{
$this->middleware('guest');
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\Models\User
*/
protected function create(array $data)
{
Admin::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
}
}
create_admin_tables.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateAdminsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('admins', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('admins');
}
}
Admin.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class Admin extends Authenticatable
{
use HasFactory,Notifiable;
protected $fillable = [
'name',
'email',
'password',
];
protected $hidden = [
'password',
'remember_token',
];
}
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' => 'web',
'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", "token"
|
*/
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'admin' => [
'driver' => 'session',
'provider' => 'admins',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
'hash' => false,
],
],
/*
|--------------------------------------------------------------------------
| 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' => App\Models\User::class,
],
'admins' => [
'driver' => 'eloquent',
'model' => App\Models\Admin::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 the reset token should 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,
],
'admins' => [
'provider' => 'admins',
'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,
];

multi authentication system in laravel

I am creating multi authentication system in laravel, I have created two sperate tables for each entity, everything works fine, but I am facing only one issue after register, users who are using web guard they can log in automatically and redirect to the user dashboard and it is perfect, but in case of other users who are using different guard, when they complete the registration process, they can not log in the system automatically.
so my question how can I enable the automatic login process for other user type once they complete the register step? below is the code that I am using in my project
Route File
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Auth::routes(['verify' => true]);
Route::get('/home', 'HomeController#index')->name('home')->middleware('verified');
Route::get('/seller/dashboard', 'SellerHomeController#index')->name('seller.dashboard');
Route::get('/seller/login','Auth\Seller\SellerLoginController#showLoginForm')->name('seller.login');
Route::post('/seller/login','Auth\Seller\SellerLoginController#login');
Route::post('/seller/logout','Auth\Seller\SellerLoginController#logout')->name('seller.logout');
Route::post('/seller/password/email','Auth\Seller\SellerForgotPasswordController#sendResetLinkEmail')->name('seller.password.email');
Route::get('/seller/password/reset', 'Auth\Seller\SellerForgotPasswordController#showLinkRequestForm')->name('seller.password.request');
Route::post('/seller/password/reset','Auth\Seller\SellerResetPasswordController#reset')->name('seller.password.update');
Route::get('/seller/password/reset/{token}', 'Auth\Seller\SellerResetPasswordController#showResetForm')->name('seller.password.reset');
Route::get('/seller/register','Auth\Seller\SellerRegisterController#showRegistrationForm')->name('seller.register');
Route::post('/seller/register','Auth\Seller\SellerRegisterController#register');
SellerLoginController
namespace App\Http\Controllers\Auth\Seller;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class SellerLoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo = '/seller/dashboard';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest:seller')->except('logout');
}
public function showLoginForm()
{
return view('auth.seller.login');
}
protected function attemptLogin(Request $request)
{
return $this->guard('seller')->attempt(
$this->credentials($request), $request->filled('remember')
);
}
protected function guard()
{
return Auth::guard('seller');
}
}
SellerRegisterController
namespace App\Http\Controllers\Auth\Seller;
use App\Seller;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Auth\Events\Registered;
class SellerRegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* #var string
*/
protected $redirectTo = '/seller/dashboard';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest:seller');
}
public function showRegistrationForm()
{
return view('auth.seller.register');
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'firstname' => ['required', 'string', 'max:255'],
'lastname' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:sellers'],
'business_name' => ['required', 'string', 'max:255'],
'business_description' => ['required', 'string', 'max:255'],
'business_location' => ['required', 'string', 'max:255'],
'business_website' => ['required', 'string', 'max:255'],
'password' => ['required', 'string', 'min:6', 'confirmed'],
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\User
*/
protected function create(array $data)
{
$seller = Seller::create([
'firstname' => $data['firstname'],
'lastname' => $data['lastname'],
'email' => $data['email'],
'business_name' => $data['business_name'],
'business_description' => $data['business_description'],
'business_location' => $data['business_location'],
'business_website' => $data['business_website'],
'business_logo' => 'test_logo.jpg',
'password' => Hash::make($data['password']),
'user_type' => $data['user_type'],
]);
return $seller;
}
}// code end here
This happens because you didn't defined the guard method on the SellerRegisterController and the default implementation retrieves the default driver (which is web).
That guard method provides the guard to the automatic login process in the register method of the RegistersUsers:
$this->guard()->login($user);
You have to override the guard method in your SellerRegisterController class to return the correct driver and allow the trait to perform the login process on the correct sellers driver:
/**
* Get the guard to be used during registration.
*
* #return \Illuminate\Contracts\Auth\StatefulGuard
*/
protected function guard()
{
return Auth::guard('sellers');
}
Laravel Auth by default take User table as the main data. In case you want to do multiple auth, first thing you need to do is create a model with Notifiable trait
Model
class Admin extends Authenticatable
{
use Notifiable;
}
After that, you need to create the guard and provider in config/auth.php
The example like this
<?php
[...]
'guards' => [
[...]
'admin' => [
'driver' => 'session',
'provider' => 'admins',
],
'writer' => [
'driver' => 'session',
'provider' => 'writers',
],
],
[...]
And
[...]
'providers' => [
[...]
'admins' => [
'driver' => 'eloquent',
'model' => App\Admin::class,
],
'writers' => [
'driver' => 'eloquent',
'model' => App\Writer::class,
],
],
[...]
And in the login controller, you will need to check which guard is trying to login by doing this line
Auth::guard('admin')->attempt(['email' => $request->email, 'password' => $request->password], $request->get('remember'))
If you need more detail about it, try to read this https://pusher.com/tutorials/multiple-authentication-guards-laravel
// Adminmiddleware
if(Auth::check() && Auth::user()->role->id == 1)
{
return $next($request);
}else {
return redirect()->route('login');
}
// Authormiddleware
if(Auth::check() && Auth::user()->role->id == 2 )
{
return $next($request);
}else {
return redirect()->route('login');
}
// Admin Route
Route::group(['as'=>'admin.','prefix'=>'admin','namespace'=>'Admin','middleware'=>['auth','admin']], function (){
Route::get('dashboard','DashboardController#index')->name('dashboard');
});
// Auhtor Route
Route::group(['as'=>'user.','prefix'=>'user','namespace'=>'Author','middleware'=>['auth','user']], function (){
Route::get('dashboard','DashboardController#index')->name('dashboard');
});
// only auht route
Route::group(['middleware'=>['auth']], function(){
Route::post('favorite/{post}/add','FavoriteController#add')->name('post.favorite');
Route::post('review/{id}/add','ReviewController#review')->name('review');
Route::get('file-download/{id}', 'PostController#downloadproject')->name('project.download');
Route::post('file-download/{id}', 'PostController#downloadproject');
});

Laravel authentication login keeps giving "These credentials do not match our records."

I have setup laravel and used it's default authentication controller but I modified the table name and it's table structure and accordingly I also changed the RegisterController and LoginController. And the RegisterController is working fine and registering a new user but when ever I try to login using the login form it gives the same validation error of "These credentials do not match our records."
I have attached the following files: LoginController, RegisterController, Admin(Model), Config->auth
I have overridden the username field according to my EmailAddress field.
Admin Model
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Auth\User as Authenticatable;
class admin extends Authenticatable
{
use Notifiable;
public $table = 'admin';
public $timestamps = false;
protected $primaryKey = 'AdminId';
protected $fillable = ['FirstName', 'LastName', 'FirstName_ar','LastName_ar','EmailAddress','Password','IsActive','remember_token'];
protected $hidden = ['Password', 'remember_token'];
public function getAuthPassword()
{
return $this->Password;
}
}
Login Controller
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Auth;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\Hash;
use Illuminate\Http\Request;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
public function username()
{
return 'EmailAddress';
}
public function getRememberTokenName()
{
return "remember_token";
}
}
Register Controller
<?php
namespace App\Http\Controllers\Auth;
use App\admin;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* #var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'firstname' => 'required|string|max:255',
'lastname' => 'required|string|max:255',
'firstname_ar' => 'required|string|max:255',
'lastname_ar' => 'required|string|max:255',
'email' => 'required|string|email|max:255',
'password' => 'required|string|min:6|confirmed',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\User
*/
protected function create(array $data)
{
return admin::create([
'FirstName' => $data['firstname'],
'LastName' => $data['lastname'],
'FirstName_ar' => $data['firstname_ar'],
'LastName_ar' => $data['lastname_ar'],
'EmailAddress' => $data['email'],
'Password' => bcrypt($data['password']),
'IsActive' => 1,
'remember_token' => str_random(10)
]);
}
public function getRememberTokenName()
{
return $this->remember_token;
}
}
Config->auth.php
<?php
return [
'defaults' => [
'guard' => 'web',
'passwords' => 'admin',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'admin',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
],
'providers' => [
// 'users' => [
// 'driver' => 'eloquent',
// 'model' => App\User::class,
// ],
'admin' => [
'driver' => 'eloquent',
'model' => App\admin::class,
],
],
'passwords' => [
// 'users' => [
// 'provider' => 'users',
// 'table' => 'password_resets',
// 'expire' => 60,
// ],
'admin' => [
'provider' => 'admin',
'table' => 'password_resets',
'expire' => 60,
],
],
];
In the RegisterController, in the create method, instead of
'password' => bcrypt($data['password']), do this
'password' => Hash::make($data['password'])
Probably why your error is happening because maybe when you're registering you're using the bcrypt hashing method for the password but when you're logging, it's using a different hashing method.
Make sure to import the class
use Illuminate\Support\Facades\Hash;
at the top of your RegisterController file.
One more thing to take care of here is to make sure when you're inserting the new user record in the database, make sure to lowercase the email by default and when logging, make sure to lowercase the email too. Some databases are case sensitive by default. So you may have a problem there.
Like you have an email in the database,
Admin#example.com and when logging, you give admin#example.com, it will not match in that case.
Hope this helps.

Resources