Custom Auth

  • Steps

    Step - 1 : Add guards

    "config/auth.php" file

    
    
    
                        'guards' => [
                              'web' => [
                                  'driver' => 'session',
                                  'provider' => 'users',
                              ],
    
                              'api' => [
                                  'driver' => 'token',
                                  'provider' => 'users',
                                  'hash' => false,
                              ],
    
                              'admin' => [
                                  'driver' => 'session',
                                  'provider' => 'admins',
                              ],
                          ],
    
                          'providers' => [
                              'users' => [
                                  'driver' => 'eloquent',
                                  'model' => App\Models\User::class,
                              ],
    
                              'admins' => [
                                  'driver' => 'eloquent',
                                  'model' => App\Models\Admin::class,
                              ],
                          ],
                        

    Step - 2 : Add Admin Model

    app\Models\Admin.php

    
    
                          namespace App\Models;
    
                          use Illuminate\Foundation\Auth\User as Authenticatable;
    
                          use Illuminate\Notifications\Notifiable;
    
                          class Admin extends Authenticatable
                          {
                              use Notifiable;
    
                              protected $table = 'admins';
                              protected $guarded = array();
                          }
    
    
    
                          

    Step - 3 : Add Admin Auth Middleware

    App\Http\Middleware/Authenticate.php

    
                          namespace App\Http\Middleware;
    
                        use Illuminate\Auth\Middleware\Authenticate as Middleware;
                        use Illuminate\Support\Facades\Auth;
    
                        class Authenticate extends Middleware
                        {
                            /**
                            * Get the path the user should be redirected to when they are not authenticated.
                            *
                            * @param    \Illuminate\Http\Request  $request
                            * @return  string|null
                            */
                            protected function redirectTo($request)
                            {
                                if (Auth::guard('admin')->guest()) {
                                
                                    if ($request->ajax() || $request->wantsJson()) {
                                        return response('Unauthorized.', 401);
                                    } else {
                                    // return redirect(route('admin.login.form'));
                                        return route('admin.login.form');
                                    }
                                    
                                }
                                
                                if (! $request->expectsJson()) {
                                    return route('login');
                                }
                            }
                        }
    
                        

    app/Http/Middleware/AdminAuthenticated.php

    
    
                          namespace App\Http\Middleware;
    
                          use Closure;
                          use Illuminate\Support\Facades\Auth;
    
                          class AdminAuthenticated
                          {
                              /**
                              * Handle an incoming request.
                              *
                              * @param    \Illuminate\Http\Request  $request
                              * @param    \Closure  $next
                              * @param    string|null  $guard
                              * @return  mixed
                              */
                              public function handle($request, Closure $next, $guard = null)
                              {
                                  if (Auth::guard('admin')->guest()) {
                                      if ($request->ajax() || $request->wantsJson()) {
                                          return response('Unauthorized.', 401);
                                      } else {
                                          return redirect(route('adminLogin'));
                                      }
                                  }
                                  
                                  $response = $next($request);
    
                                  $response->headers->set('Access-Control-Allow-Origin' , '*');
                                  $response->headers->set('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE');
                                  $response->headers->set('Access-Control-Allow-Headers', 'Content-Type, Accept, Authorization, X-Requested-With, Application');
                                  $response->headers->set('Cache-Control','nocache, no-store, max-age=0, must-revalidate');
                                  $response->headers->set('Pragma','no-cache'); //HTTP 1.0
                                  $response->headers->set('Expires','Sat, 01 Jan 1990 00:00:00 GMT'); // // Date in the past
    
                                  return $response;
                                  
                              }
                          }
    
                          

    Step - 4 : Add Middlewave in Kernel.php file

    app/Http/Kernel.php

    
                          namespace App\Http;
    
                          use Illuminate\Foundation\Http\Kernel as HttpKernel;
    
                          class Kernel extends HttpKernel
                          {
                              /**
                              * The application's global HTTP middleware stack.
                              *
                              * These middleware are run during every request to your application.
                              *
                              * @var  array
                              */
                              protected $middleware = [
                                  // \App\Http\Middleware\TrustHosts::class,
                                  \App\Http\Middleware\TrustProxies::class,
                                  \Fruitcake\Cors\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
                              */
                              protected $middlewareGroups = [
                                  'web' => [
                                      \App\Http\Middleware\EncryptCookies::class,
                                      \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
                                      \Illuminate\Session\Middleware\StartSession::class,
                                      // \Illuminate\Session\Middleware\AuthenticateSession::class,
                                      \Illuminate\View\Middleware\ShareErrorsFromSession::class,
                                      \App\Http\Middleware\VerifyCsrfToken::class,
                                      \Illuminate\Routing\Middleware\SubstituteBindings::class,
                                  ],
    
                                  'admin' => [
                                      \App\Http\Middleware\EncryptCookies::class,
                                      \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
                                      \Illuminate\Session\Middleware\StartSession::class,
                                      \Illuminate\View\Middleware\ShareErrorsFromSession::class,
                                      \App\Http\Middleware\VerifyCsrfToken::class,
                                      \Illuminate\Routing\Middleware\SubstituteBindings::class,
                                  ],
    
                                  'api' => [
                                      'throttle:api',
                                      \Illuminate\Routing\Middleware\SubstituteBindings::class,
                                  ],
                              ];
    
                              /**
                              * The application's route middleware.
                              *
                              * These middleware may be assigned to groups or used individually.
                              *
                              * @var  array
                              */
                              protected $routeMiddleware = [
                                  'auth' => \App\Http\Middleware\Authenticate::class,
                                  'adminauth' => \App\Http\Middleware\AdminAuthenticated::class,
                                  'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::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' => \Illuminate\Routing\Middleware\ValidateSignature::class,
                                  'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
                                  'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
                              ];
                          }
    
    

    Step - 5 : Make Change in RouteServiceProvider.php

    "app/Providers/RouteServiceProvider.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.
              *
              * This is used by Laravel authentication to redirect users after login.
              *
              * @var  string
              */
              public const HOME = '/home';
    
              /**
              * If specified, this namespace is automatically applied to your controller routes.
              *
              * In addition, it is set as the URL generator's root namespace.
              *
              * @var  string
              */
              protected $namespace = 'App\Http\Controllers';
    
              /**
              * Define your route model bindings, pattern filters, etc.
              *
              * @return  void
              */
              public function boot()
              {
                  $this->configureRateLimiting();
    
                  $this->routes(function () {
                      Route::middleware('web')
                          ->namespace($this->namespace)
                          ->group(base_path('routes/web.php'));
    
                      Route::prefix('api')
                          ->middleware('api')
                          ->group(base_path('routes/api.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);
                  });
              }
          }
    
    
    Issue : redirect to login page after successful login Apply middleware('web') to routes/web.php, >middleware('api') to routes/api.php, middleware('admin') to routes/admin.php

    Step - 6 : Add Admin Login Routes

    "routes/web.php"

    
    
    
    Route::group(['middleware' => 'adminauth'], function () {
    	  // Admin Dashboard
    	  Route::get('dashboard','AdminController@dashboard')->name('dashboard');	
    });
    
    

    Step - 7 : Create AdminAuhController

    
    
    namespace App\Http\Controllers\Auth;
    
    use Validator;
    use Session;
    use App\Http\Controllers\Controller;
    use App\Providers\RouteServiceProvider;
    use Illuminate\Foundation\Auth\AuthenticatesUsers;
    use Illuminate\Http\Request;
    use App\Http\Requests;
    use App\\Models\Admin;
    
    class AdminAuthController 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 = '/admin/login';
    
        /**
         * Create a new controller instance.
         *
         * @return  void
         */
        public function __construct()
        {
            $this->middleware('guest', ['except' => 'logout']);
        }
    
        public function getLogin()
        {
            return view('auth.admin.login');
        }
    
        /**
         * Show the application loginprocess.
         *
         * @return  \Illuminate\Http\Response
         */
        public function postLogin(Request $request)
        {
            $this->validate($request, [
                'email' => 'required|email',
                'password' => 'required',
            ]);
            if (auth()->guard('admin')->attempt(['email' => $request->input('email'), 'password' => $request->input('password')]))
            {
                $user = auth()->guard('admin')->user();
                
                \Session::put('success','You are Login successfully!!');
                return redirect()->route('dashboard');
                
            } else {
                return back()->with('error','your username and password are wrong.');
            }
    
        }
    
        /**
         * Show the application logout.
         *
         * @return  \Illuminate\Http\Response
         */
        public function logout()
        {
            auth()->guard('admin')->logout();
            \Session::flush();
            \Sessioin::put('success','You are logout successfully');        
            return redirect(route('adminLogin'));
        }
    }
    
    

    Step - 8 : Create AdminController

    
    namespace App\Http\Controllers;
    
    use App\Http\Requests;
    use Illuminate\Http\Request;
    
    class AdminController extends Controller
    {
        /**
         * Show the application dashboard.
         *
         * @return  \Illuminate\Http\Response
         */
        public function dashboard()
        {
            return view('admin.dashboard');
        }
    }