如果用户未使用中间件进行身份验证,Laravel 5.4 将重定向到特定页面

Posted

技术标签:

【中文标题】如果用户未使用中间件进行身份验证,Laravel 5.4 将重定向到特定页面【英文标题】:Laravel 5.4 redirect to specific page if user is not authenticated using middleware 【发布时间】:2017-09-22 06:10:03 【问题描述】:

如果未通过身份验证,我想将用户重定向到我的索引页面(即登录页面)

似乎无法让它工作,我真的对路由感到困惑。

家庭控制器

class HomeController extends Controller


    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    
        return redirect()->guest('/');
    

路由

// Index
Route::get('/', [
    'as' => 'index',
    'uses' => 'UserController@index'
]);

用户控制器

您看到的路由重定向到 index 函数中的 用户控制器,如下所示:

*有 __construct() 所以它使用中间件'auth'。

public function __construct()

    $this->middleware('auth');


public function index()

    // If user is logged
    if(Auth::check()) 

        // If user has NOT submitted information form redirect there, otherwise to categories
        if(!Auth::user()->submitted_information)
            return redirect()->route('information');
        else
            return redirect()->route('categories');
    
    else
        return view('index', ['body_class' => 'template-home']);


处理程序.php

还有auth中间件里面的未认证功能(Exceptions/Handler.php)

 protected function unauthenticated($request, AuthenticationException $exception)
    
        if ($request->expectsJson()) 
            return response()->json(['error' => 'Unauthenticated.'], 401);
        

        return redirect()->route('index');
    

我现在得到的错误如下:

InvalidArgumentException in UrlGenerator.php line 304:
Route [index] not defined.

发生这个错误是因为

的行

return redirect()->route('index'); 在上面的unauthenticated函数中。

我在这里缺少什么?如果您需要更多信息,请随时询问。

EDIT :到目前为止,如果我从 UserController 中删除 __construct() 方法,并将 web.php 插入到所有路由中 middleware 使用什么,它有效。

例如

Route::get('/categories', [
    'as' => 'categories',
    'uses' => 'UserController@showCategories'
])->middleware('auth');

但我试图找到自动使用它,但没有指定要使用的中间件。

【问题讨论】:

【参考方案1】:

按照以下代码构建您的路线:

Route::group(['middleware' => ['auth']], function() 
     // uses 'auth' middleware
     Route::resource('blog','BlogController');
);

Route::get('/mypage', 'HomeController@mypage');

打开名为 RedirectIfAuthenticated 的中间件类,然后在处理函数中 你写下面的代码:

if (!Auth::check()) 
     return redirect('/mypage'); // redirect to your specific page which is public for all

希望它对你有用。

【讨论】:

【参考方案2】:

试试

Route::get('/','UserController@index',['middleware'=>'auth'])->name('index);

【讨论】:

【参考方案3】:

你的路线应该是这样的

// 索引

Route::get('/','UserController@index')->name('index);

see here 了解有关路由的更多信息。

【讨论】:

不,这没有帮助..它有助于显示正确的路由,但现在有一个网络循环一直在命中“/”

以上是关于如果用户未使用中间件进行身份验证,Laravel 5.4 将重定向到特定页面的主要内容,如果未能解决你的问题,请参考以下文章

Laravel & VueJS CORS 尝试对用户进行身份验证时出现问题,即使使用 Cors 中间件也是如此

如何使用 API 中间件在 Laravel 中测试 PHPUnit 一个经过身份验证的用户?

身份验证用户提供程序 [passport] 未使用 laravel 护照定义

Laravel 5.3 中间件:创建用于身份验证的中间件

在Laravel中使用Middleware进行身份验证

有没有办法在 laravel 的不同数据库中对用户进行身份验证?