dqrmkdu25623 2016-07-08 11:21
浏览 89

如果未经过身份验证,laravel 5.2中的路由不会自动重定向到登录

I have done multiple authentication in Laravel 5.2, everything is working fine . I am able to authenticate admin,redirect to dashboard and logout successfully. But the problem is that when user is not authenticated and I put route of dashboard in url then it opens dashboard even if admin is not authenticated.

My Admin Model

<?php

 namespace App\Models;

 use Illuminate\Foundation\Auth\User as Authenticatable;

 class System_admin extends Authenticatable
{
protected $guard="admins";
protected $table="system_admin";
protected $primaryKey="admin_id"; 
protected $fillable = [
    'admin_name', 'admin_email', 'admin_password','city_id','admin_address','admin_mobile','admin_status'
];

public function getAuthPassword() {
    return $this->admin_password;
}
}

My 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", "token"
|
*/

'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],

    'api' => [
        'driver' => 'token',
        'provider' => 'users',
    ],

    //for admin
    'admins' => [
        '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,
    ],

    //for admin
    'admins' => [
        'driver' => 'eloquent',
        'model' => App\Models\System_admin::class,
    ],

    // 'users' => [
    //     'driver' => 'database',
    //     'table' => 'users',
    // ],
],

/*
|--------------------------------------------------------------------------
| Resetting Passwords
|--------------------------------------------------------------------------
|
| Here you may set the options for resetting passwords including the view
| that is your password reset e-mail. You may also set the name of the
| table that maintains all of the reset tokens for your application.
|
| 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',
        'email' => 'auth.emails.password',
        'table' => 'password_resets',
        'expire' => 60,
    ],

    'admins' => [
        'provider' => 'admins',
        'email' => 'auth.emails.password',
        'table' => 'password_resets',
        'expire' => 60,
    ],

],

];

My Middleware AdminAuth.php

      <?php

namespace App\Http\Middleware;

 use Closure;
 use Illuminate\Support\Facades\Auth;

 class AdminAuth
 {
 /**
 * 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 = 'admins')
{
    if (Auth::guard($guard)->guest()) {
        if ($request->ajax()) {
            return response('Unauthorized.', 401);
        } else {
            return redirect()->guest('/admin');
        }
    }

    return $next($request);
}
}

app/kernel.php

      <?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 = [
    \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::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\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
    ],

    'admins' => [
        \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',
    ],



];

/**
 * The application's route middleware.
 *
 * These middleware may be assigned to groups or used individually.
 *
 * @var array
 */
protected $routeMiddleware = [
    'admins' => \App\Http\Middleware\AdminAuth::class,
    '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,
];
}

LoginController.php

 <?php

namespace App\Http\Controllers\admin;

use Illuminate\Http\Request;

 use App\Http\Requests;
use App\Http\Controllers\Controller;

use \Auth;
use Session;

class LoginController extends Controller
{
public function viewlogin()
{
    return view('admin.login');
}

public function checklogin(Request $request)
{
     $credentials=array('admin_email' => $request->input('email'),'password' => $request->input('password'));

     if(Auth::guard('admins')->attempt($credentials)) 
         return redirect()->intended('/admin/dashboard');
     else
        return redirect('/admin')->with('error','Invalid Username or Password');
}

public function logout()
{
    Auth::guard('admins')->logout();
    return redirect()->intended('/admin');
}
}

Routes

 Route::group(['middleware' => ['admins']], function () 
 {

Route::get('/admin','Admin\LoginController@viewlogin');
Route::post('/admin/login','Admin\LoginController@checklogin');


Route::get('/admin/dashboard','Admin\AdminController@dashboard');
Route::get('/admin/logout','Admin\LoginController@logout');
Route::resource('/admin/movies','Admin\MovieController');
Route::resource('/admin/states','Admin\StateController');
Route::resource('/admin/cities','Admin\CityController');
Route::resource('/admin/tax','Admin\TaxController');
Route::resource('/admin/smsgateway','Admin\SmsgatewayController');
Route::resource('/admin/smtpgateway','Admin\SmtpgatewayController');
Route::resource('/admin/paymentgateway','Admin\PaymentgatewayController');

 });



Route::group(['middleware' => ['web']], function () {


 });

When I am logged in and I open Dashboard then I can see the credentials of logged admin.

enter image description here

But when I log out, and again visit dashboard it should redirect to login but it's not redirecting to login page.

enter image description here

Kindly help me as none of questions on stackoverflow has got the answer which I am looking for.

  • 写回答

2条回答 默认 最新

  • donv29560 2016-07-08 11:28
    关注

    have you added the auth middleware etc

     Route::group(['middleware' => ['admins', 'auth']], function (){..}
    

    As this will do the checking for users etc, also within 5.2 you no longer need the middleware webas well, as this is baked into the system automatically.

    评论

报告相同问题?

悬赏问题

  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)