I'm using JWT-auth with Laravel Framework to authenticate a user. Laravel is used as server-end framework and the fore-end code is in the framework which is developed by our own. So we use api not web to realize authentication. Login works well in this environment, whereas logout and refresh token can't perform as I wish. I configure everything as JWT-auth documentation says.
route.php
Route::group(['middleware' => 'api', 'prefix' => 'user', 'namespace' => 'User'], function () {
Route::post('/login', 'AuthController#login'); // login
Route::post('/logout', 'AuthController#logout'); // logout (invalidate token)
Route::post('/refresh', 'AuthController#refresh'); // refresh token});
kernel.php
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,
],
'api' => [
'throttle:60,1',
'bindings',
],
];
auth.php
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'jwt',
'provider' => 'users',
],
],
'providers' => [
'users' => [
'driver' => 'password',
'model' => App\User::class,
],
/*'users' => [
'driver' => 'database',
'table' => 'user',
],*/
],
User\AuthController
<?php
namespace App\Http\Controllers\User;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use AjaxResponse;
use Log;
class AuthController extends Controller
{
/**
* Create a new AuthController instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth:api', ['except' => ['login']]);
}
/**
* login
* #param Request $request
* #return mixed
*/
public function login(Request $request)
{
$credentials = $request->only('phone', 'password');
if (! $token = auth()->attempt($credentials)) {
return AjaxResponse::fail(4001);
}
return $this->respondWithToken($token);
}
/**
* logout(invalidate token)
* #return \Illuminate\Http\JsonResponse
*/
public function logout()
{
Log::debug('yyyyyyyyy');
auth()->logout();
return AjaxResponse::succeed(['message' => 'Successfully logged out']);
}
/**
* refresh token
* #return \Illuminate\Http\JsonResponse
*/
public function refresh()
{
return $this->respondWithToken(auth()->refresh());
}
/**
* get token structure
* #param $token
* #return mixed
*/
protected function respondWithToken($token)
{
if (Auth::user()['deleted_at'] || ! Auth::user()['is_active'])
return AjaxResponse::fail(4001);
else
return AjaxResponse::succeed([
'access_token' => $token,
'token_type' => 'bearer',
'expires_in' => auth()->factory()->getTTL() * 60,
'user_name' => Auth::user()['name'],
'user_admin' => (bool)Auth::user()['is_admin']
]);
}
}
'yyyyyyyyy' can't be logged. So it seems that the logout function in AuthController wasn't called.
Is there anything wrong I've written or missed? Thanks in advance.
After a few tryings, I've changed the AuthController's constructor and it worked.
User\AuthController
public function __construct()
{
$this->middleware('auth:api', ['except' => ['login', 'refresh', 'logout']]);
}
I've added functions as value of 'except', in which I expected to invalidate the present session.
Related
I am working on a big project that has a laravel backend for API and a separate SPA (vue-cli scaffolded).
they are found on the same top level domain the laravel project runs at the domain(m.m) and the Vue Spa runs at(vue.m.m:8080)
what my problem is:
auth:sanctum protected routes does not work they return ({ "message" : "Unauthenticated" })
what works:
route /api/login works perfectly when given the correct password and email (it sends a response ({"message" : "Login successful"}))
my code snippets:
.env (it is only the part that is needed based on the docs I cant show the other because of security issues)
BROADCAST_DRIVER=log
CACHE_DRIVER=file
QUEUE_CONNECTION=sync
SESSION_DRIVER=cookie
SESSION_LIFETIME=120
SESSION_DOMAIN=.m.m
SANCTUM_STATEFUL_DOMAINS=vue.m.m
backend
UserController => for Authenticating
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\User;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
class UserController extends Controller
{
public function register(Request $request)
{
$this->validator($request->all())->validate();
$user = $this->create($request->all());
$this->guard()->login($user);
return response()->json(['user'=> $user,
'message'=> 'registration successful'
], 200);
}
/**
* 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:4', 'confirmed'],
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\User
*/
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
}
protected function guard()
{
return Auth::guard();
}
public function login(Request $request)
{
$credentials = $request->only('email', 'password');
if (Auth::attempt($credentials)) {
// Authentication passed...
return response()->json(['message' => 'Login successful'], 200);
}
}
public function logout()
{
Auth::logout();
return response()->json(['message' => 'Logged Out'], 200);
}
}
sactum.php
<?php
return [
'stateful' => explode(',', env(
'SANCTUM_STATEFUL_DOMAINS',
'localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,::1'
)),
'expiration' => null,
'middleware' => [
'verify_csrf_token' => App\Http\Middleware\VerifyCsrfToken::class,
'encrypt_cookies' => \Illuminate\Cookie\Middleware\EncryptCookies::class,
],
];
auth.php
<?php
return [
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
'hash' => false,
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
'throttle' => 60,
],
],
'password_timeout' => 10800,
];
User Model
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasFactory, Notifiable,HasApiTokens;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
api.php
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return "protected route";
});
Route::post("/login","App\Http\Controllers\UserController#login");
cors.php (for development purposes I allowed all incoming requests to be processed) and (credentials are set to true)
'paths' => ['*'],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => true,
kernel.php
protected $middleware = [
// \App\Http\Middleware\TrustHosts::class,
\Fruitcake\Cors\HandleCors::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,
];
'api' => [
\Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
Frontend
axios
axios.defaults.withCredentials = true;
axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
axios.defaults.baseURL = 'http://m.m/api';
Vue (this is the method that handles sending login requests)
login(evt) {
evt.preventDefault();
axios.get("/sanctum/csrf-cookie", { baseURL: "http://m.m" }).then(() => {
axios
.post(
"/login",
{ email: "john#doe.com", password: "password" },
)
.then(() => {
const res = axios.get("/user");
console.log(res.data);
});
});
};
}
what I get from the browser
network tab from chrome
this is what is stored in the browser as cookies
(image)
I had the same problem. I solved as the following:
In the api routes define
Route::get('/unauthenticated', function () {
return response()->json(["message" : "unauthenticated"]);
})->name('api.unauthenticated');
Now in the method redirectTo in the Authenticate.php middleware add this line
if ($request->is('api/*') || $request->is('api'))
return route('api.unauthenticated');
And that's it.
It works for me
I want to Multi Auth with single table in laravel 5.2.
I tried this way. But frontend login working.
Laravel 5.2 has a new artisan command.
php artisan make:auth
it will generate basic login/register route, view and controller for user table.
Make a admin table as users table for simplicity.
Controller For Admin
app/Http/Controllers/AdminAuth/AuthController
app/Http/Controllers/AdminAuth/PasswordController
(note: I just copied these files from app/Http/Controllers/Auth/AuthController here)
config/auth.php
//Authenticating guards
return [
'guards' => [
'user' =>[
'driver' => 'session',
'provider' => 'user',
],
'admin' => [
'driver' => 'session',
'provider' => 'admin',
],
],
//User Providers
'providers' => [
'user' => [
'driver' => 'database',
'table' => 'user',
'model' => App\User::class,
],
'admin' => [
'driver' => 'database',
'table' => 'user',
'model' => App\Admin::class,
]
],
//Resetting Password
'passwords' => [
'clients' => [
'provider' => 'client',
'email' => 'auth.emails.password',
'table' => 'password_resets',
'expire' => 60,
],
'admins' => [
'provider' => 'admin',
'email' => 'auth.emails.password',
'table' => 'password_resets',
'expire' => 60,
],
],
];
route.php
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');
});
AdminAuth/AuthController.php
Add two methods and specify $redirectTo and $guard
protected $redirectTo = '/admin';
protected $guard = 'admin';
public function showLoginForm()
{
if (view()->exists('auth.authenticate')) {
return view('auth.authenticate');
}
return view('admin.auth.login');
}
public function showRegistrationForm()
{
return view('admin.auth.register');
}
it will help you to open another login form for admin
creating a middleware for admin
class RedirectIfNotAdmin
{
/**
* 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 = 'admin')
{
if (!Auth::guard($guard)->check()) {
return redirect('/');
}
return $next($request);
}
}
register middleware in kernel.php
protected $routeMiddleware = [
'admin' => \App\Http\Middleware\RedirectIfNotAdmin::class,
];
use this middleware in AdminController
e.g.,
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
class AdminController extends Controller
{
public function __construct(){
$this->middleware('admin');
}
public function index(){
return view('admin.dashboard');
}
}
In your AdminAuth/AuthController.php.
public function guard()
{
return auth()->guard('admin');
}
and instead of give table name inside providers put protected $table = 'users' in your Admin model.
You can see this for further more details: https://scotch.io/#sukelali/how-to-create-multi-table-authentication-in-laravel
You don't need to use a guard here, Instead; you can use middleware here. Add a user type column here in user table and then create middleware for that.
I am learning laravel and i decided to make a custom authentication in laravel . I could register my users but when i try to login i get this error ?
Type error: Argument 2 passed to Illuminate\Auth\SessionGuard::__construct() must implement interface Illuminate\Contracts\Auth\UserProvider, null given,
These are my resources
My AdminUser Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model as Eloquent;
use Illuminate\Notifications\Notifiable;
use Illuminate\Auth\Authenticatable as AuthenticableTrait;
use Illuminate\Foundation\Auth\Access\Authorizable;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
class AdminUser extends Eloquent implements AuthenticatableContract,AuthorizableContract
{
public $table = "admin_users";
use Notifiable;
use AuthenticableTrait;
use Authorizable;
protected $fillable = [
'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
My AdminUserController
<?php
namespace App\Http\Controllers;
use App\AdminUser;
use App\Http\Controllers\Controller;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use App\Http\Requests\LoginRequest;
use App\Http\Requests\RegisterRequest;
use Auth;
use Response;
class AdminUserController extends Controller {
use AuthenticatesUsers;
/**
* the model instance
* #var AdminUser
*/
protected $user;
/**
* The Guard implementation.
*
* #var Authenticator
*/
protected $admin;
/**
* Create a new authentication controller instance.
*
* #param Authenticator $admin
* #return void
*/
public function __construct(Guard $admin, AdminUser $user)
{
$user = AdminUser::first();
Auth::login($user);
$this->middleware('admin', ['except' => ['getLogout']]);
}
/**
* Show the application registration form.
*
* #return Response
*/
public function getRegister()
{
return view('admin/admin_users/register');
}
/**
* Handle a registration request for the application.
*
* #param RegisterRequest $request
* #return Response
*/
public function postRegister(RegisterRequest $request)
{
AdminUser::create([
'email' => $request->email,
'password' => bcrypt($request->password),
]);
return redirect('backend-admin/dashboard');
}
/**
* Show the application login form.
*
* #return Response
*/
public function getLogin()
{
return view('admin/admin_users/login');
}
/**
* Handle a login request to the application.
*
* #param LoginRequest $request
* #return Response
*/
public function postLogin(LoginRequest $request)
{
if (Auth::guard('admin')->attempt($request->only('email', 'password')))
{
return redirect()->intended('/backend-admin/dashboard');
}
return redirect('/backend-admin')->withErrors([
'email' => 'The credentials you entered did not match our records. Try again?',
]);
}
/**
* Log the user out of the application.
*
* #return Response
*/
public function getLogout()
{
Auth::guard('admin')->logout();
return redirect('/backend-admin');
}
protected function guard()
{
return Auth::guard();
}
}
My VerifyAdmin Middleware
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Support\Facades\Auth;
class VerifyAdmin
{
/**
* The Guard implementation.
*
* #var Guard
*/
protected $admin;
/**
* Create a new filter instance.
*
* #param Guard $auth
* #return void
*/
public function __construct(Guard $auth)
{
// dd($auth);
$this->admin = $auth;
}
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if ($this->admin->guest())
{
if ($request->ajax())
{
return response('Unauthorized.', 401);
}
else
{
return redirect()->guest('backend-admin');
}
}
return $next($request);
}
}
I also defined guards in auth.php
<?php
return [
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
'admin' => [
'driver' => 'session',
'provider' => 'admins',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'admin' => [
'driver' => 'eloquent',
'model' => App\AdminUser::class,
],
],
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
],
],
];
Also defined middleware in kernel.php
protected $routeMiddleware = [
'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'admin' => \App\Http\Middleware\VerifyAdmin::class,
Feel free to correct me if i am wrong anywhere or if i have missed anything .
I found what was bugging my program , i did defined guard function in my controller but forget to add the guard in function , i fixed it by defining guard.
I think the problem are those 2 lines:
$user = AdminUser::first();
Auth::login($user);
What's the point of running it? First of all, I see you have here login action and it seems you automatically login admin when on login page - it doesn't make much sense.
Also those 2 lines won't do anything that should be done I think - because when admin logs in, well you log him in so there's no point to login him in each request assuming you are using sessions.
You need to change the admin provider name from admin to admins.
<?php
return [
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
'admin' => [
'driver' => 'session',
'provider' => 'admins',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'admins' => [ // ***this is the change that should be made***
'driver' => 'eloquent',
'model' => App\AdminUser::class,
],
],
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
],
],
];
I'm trying to set up two authentication guards: internal (for normal browser requests) and api for AJAX requests. api is the default guard, but I'm focusing on getting the internal-guard to work, for now.
This is my config/auth.php:
<?php
return [
'defaults' => [
'guard' => 'api',
'passwords' => 'clients',
],
'guards' => [
'internal' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'clients',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'clients' => [
'driver' => 'eloquent',
'model' => App\Client::class,
],
],
'passwords' => [
'users' => [
'provider' => 'users',
'email' => 'auth.emails.password',
'table' => 'password_resets',
'expire' => 60,
],
],
];
This is my routes.php:
<?php
Route::group([
'domain' => 'internal.example.com',
'middleware' => ['web', 'auth:internal']
], function () {
Route::get('/', function () {
return view('welcome');
});
Route::get('/home', 'HomeController#index');
});
Route::group([
'domain' => 'internal.example.com',
'middleware' => [ 'web']
], function () {
Route::match(['get', 'post'], '/login', 'InternalAuth\InternalAuthController#login');
Route::get('/logout', 'InternalAuth\InternalAuthController#logout');
});
This is InternalAuthController:
<?php
namespace App\Http\Controllers\InternalAuth;
use App\User;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
class InternalAuthController extends Controller
{
/*
|--------------------------------------------------------------------------
| Registration & Login Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users, as well as the
| authentication of existing users. By default, this controller uses
| a simple trait to add these behaviors. Why don't you explore it?
|
*/
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
/**
* Where to redirect users after login / registration.
*
* #var string
*/
protected $redirectTo = '/';
protected $guard = 'internal';
/**
* Create a new authentication controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest', ['except' => 'logout']);
}
/**
* 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|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|confirmed|min:6',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
}
Seems fine to me. But when I go to /, /home or /login in my browser, I end up in a redirect loop.
I'm missing something... Any ideas?
/login points to InternalAuth\InternalAuthController#login. login() is a method of Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers (used by InternalAuth), but it is not responsible for returning the view or responding to post requests. This is a job for getLogin and postLogin.
So, I needed to change this in the routes.php:
Route::match(['get', 'post'], '/login', 'InternalAuth\InternalAuthController#login');
To this:
Route::get('/login', 'InternalAuth\InternalAuthController#getLogin');
Route::post('/login', 'InternalAuth\InternalAuthController#postLogin');
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 6 years ago.
Improve this question
Does anyone know how to use multi authenticate in laravel 5.2 ! I want to use It but I don't know how ?
does anyone has a tutorial or project setting up multi authentication?
You need two tables users and admins
Run command following command to create built in auth
php artisan make:auth
Two models Users(Already exist) and Admin
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
class Admin extends Authenticatable
{
}
Now open config/auth.php and make the following changes
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'admin' => [
'driver' => 'session',
'provider' => 'admins',
],
],
'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' => 'auth.emails.password',
'table' => 'password_resets',
'expire' => 60,
],
],
Create a new Middleware RedirectIfNotAdmin
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class RedirectIfNotAdmin
{
/**
* 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 = 'admin')
{
if (!Auth::guard($guard)->check()) {
return redirect('/admin/login');
}
return $next($request);
}
}
Changes in Kernel.php
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
];
protected $middlewareGroups = [
'web' => [
\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,
],
'api' => [
'throttle:60,1',
],
];
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'admin' => \App\Http\Middleware\RedirectIfNotAdmin::class,
];
Create a new folder Http/Controller/Adminauth and copy the files from Http/Controller/Auth folder
Open the file Http/Controller/Adminauth/AuthController.php and make the following changes
<?php
namespace App\Http\Controllers\Adminauth;
use App\Admin;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
use Auth;
class AuthController extends Controller
{
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
protected $redirectTo = '/admin';
protected $guard = 'admin';
public function showLoginForm()
{
if (Auth::guard('admin')->check())
{
return redirect('/admin');
}
return view('admin.auth.login');
}
public function showRegistrationForm()
{
return view('admin.auth.register');
}
public function resetPassword()
{
return view('admin.auth.passwords.email');
}
public function logout(){
Auth::guard('admin')->logout();
return redirect('/admin/login');
}
}
Create new folder Http/Controller/admin, copy Controller.php file in the folder from Http/Controller/
create new file Http/Controller/admin/employee.php
<?php
namespace App\Http\Controllers\admin;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Auth;
use App\Admin;
class Employee extends Controller
{
public function __construct(){
$this->middleware('admin');
}
public function index(){
return view('admin.home');
}
}
move to resources/views create new folder resources/views/admin
copy
resources/views/auth, resources/views/layouts & resources/views/home.blade.php
and post into resources/views/admin and open the each file in admin folder and add admin before each path, Now the path should look like
#extends('admin.layouts.app')
and your Http/routes.php look like
<?php
Route::get('/', function () {
return view('welcome');
});
Route::get('/admin/login','Adminauth\AuthController#showLoginForm');
Route::post('/admin/login','Adminauth\AuthController#login');
Route::get('/admin/password/reset','Adminauth\PasswordController#resetPassword');
Route::group(['middleware' => ['admin']], function () {
//Login Routes...
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', 'Admin\Employee#index');
});
Route::group(['middleware' => 'web'], function () {
Route::auth();
Route::get('/home', 'HomeController#index');
});
Thats it open your site in browser and check
and for admin yoursiteurl/admin
Enjoy....
First, we create two models: user and admin
Then, we update the config/auth.php file:
return [
'defaults' => [
'guard' => 'user',
'passwords' => 'user',
],
'guards' => [
'user' => [
'driver' => 'session',
'provider' => 'user',
],
'admin' => [
'driver' => 'session',
'provider' => 'admin',
],
],
'providers' => [
'user' => [
'driver' => 'eloquent',
'model' => 'App\User',
],
'admin' => [
'driver' => 'eloquent',
'model' => 'App\Admin',
],
],
'passwords' => [
'user' => [
'provider' => 'user',
'email' => 'auth.emails.password',
'table' => 'password_resets',
'expire' => 60,
],
'admin' => [
'provider' => 'admin',
'email' => 'auth.emails.password',
'table' => 'password_resets',
'expire' => 60,
]
]
];
Now, modify the app/Http/kernel.php file:
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class
];
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class
],
'api' => [
'throttle:60,1',
],
];
Create LoginController and set the following code in it.
Note: You have to create login pages for 'user' as well as 'admin'. You then have to submit login form requests to the appropriate controller function i.e. userLogin() or adminLogin().
namespace App\Http\Controllers;
use Auth, Input;
use App\User;
use App\Admin;
class LoginController extends Controller
{
public function userLogin(){
$input = Input::all();
if(count($input) > 0){
$auth = auth()->guard('user');
$credentials = [
'email' => $input['email'],
'password' => $input['password'],
];
if ($auth->attempt($credentials)) {
return redirect()->action('LoginController#profile');
} else {
echo 'Error';
}
} else {
return view('user.login');
}
}
public function adminLogin(){
$input = Input::all();
if(count($input) > 0){
$auth = auth()->guard('admin');
$credentials = [
'email' => $input['email'],
'password' => $input['password'],
];
if ($auth->attempt($credentials)) {
return redirect()->action('LoginController#profile');
} else {
echo 'Error';
}
} else {
return view('admin.login');
}
}
public function profile(){
if(auth()->guard('admin')->check()){
pr(auth()->guard('admin')->user()->toArray());
}
if(auth()->guard('user')->check()){
pr(auth()->guard('user')->user()->toArray());
}
}
}
In most cases I just add a field to the user table called usertype and pass appropriate values like 0=admin, 1=user etc.
This approach helps in avoiding the unnecessary headache of creating different user roles or types.
Though this may not sound ideal, but helps in saving lots of time.