欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

Laravel 5.4 5.5 定义中间件,没有登录访问后台跳转到指定页面 未登录跳转 laravel 5.5 5.4 有大用 有大大用

主要目的就是结合中间件,如果用户没有登录打开后台,实现跳转到指定页面。

1: php artisan make:middleware AdminLogin             

这样Http下面的Middleware会生成AdmnLogin.php

2:里面写handle方法如下,这个结合自己的写,指定跳转到页面

[php] view plain copy                    
  1. public function handle($request, Closure $next)  

  2.     {  

  3.         $check = \Auth::guard('admin')->check();  

  4.         if(!$check){  

  5.             return redirect('admin/login');  

  6.         }  

  7.         return $next($request);  

  8.     }  

3:在Http下面的Kernel.php里的protected $routeMiddleware加上路由中间件

[php] view plain copy                    
  1. //后台登录保护中间件  

  2.         'admin.login' => \App\Http\Middleware\AdminLogin::class,  

 个人分类: Laraver             

来自  https://blog.csdn.net/myarche/article/details/79738417


 
活动时间 1年,1个月前    
观看了 30k次    
 Laravel < 5.5我可以更改此文件app/Exceptions/Handler以更改未经身份验证的用户重定向网址:                                 
protected function unauthenticated($request, AuthenticationException $exception)
{
    if ($request->expectsJson()) {
        return response()->json(['error' => 'Unauthenticated.'], 401);
    }

    return redirect()->guest(route('login'));
}
                   

但是Laravel 5.5这里已经移到了这个位置,vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php所以现在如何更改?我不想更改供应商目录中的内容,以防它被作曲家更新所覆盖。                    

protected function unauthenticated($request, AuthenticationException $exception)
{
    return $request->expectsJson()
                ? response()->json(['message' => 'Unauthenticated.'], 401)
                : redirect()->guest(route('login'));
}
               
                      

                           
添加评论                
       

8个答案        正确答案        


           
       
58                        

但是在Laravel 5.5中,此位置已移至该位置vendor / laravel / framework / src / Illuminate / Foundation / Exceptions / Handler.php,所以现在如何更改它?我不想更改供应商目录中的内容,以防它被作曲家更新所覆盖。                            

只是默认情况下不再存在该功能。                        

您可以像在5.4中一样重写它。只要确保包括                        

use Exception;
use Request;
use Illuminate\Auth\AuthenticationException;
use Response;
                       

在处理程序文件中。                        

例如我app/Exceptions/Handler.php看起来像这样:                        

<?php
    namespace App\Exceptions;
    use Exception;
    use Request;
    use Illuminate\Auth\AuthenticationException;
    use Response;
    use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
    class Handler extends ExceptionHandler
    {
        (...) // The dfault file content
        /**
         * Convert an authentication exception into a response.
         *
         * @param  \Illuminate\Http\Request  $request
         * @param  \Illuminate\Auth\AuthenticationException  $exception
         * @return \Illuminate\Http\Response
         */
         protected function unauthenticated($request, AuthenticationException $exception)
         {
            return $request->expectsJson()
                    ? response()->json(['message' => 'Unauthenticated.'], 401)
                    : redirect()->guest(route('authentication.index'));
    }
}
                   

               
  • 1个                                    
    我找到的最佳答案,谢谢!只是一件事:有没有一种方法可以使用请求路由通过api路由而不是使用ExpectsJson()? –  Dave Nottage '17 Nov 2'在22:53                                    
  • 你们真是棒极了,我当时想禁用Web中间件,但是这种解决方案是最好的。 – 安德烈斯·菲利普 (  Andres Felipe)18年1月12日在13:07                                    
  • 3                                    
    if (in_array('api', \Route::getCurrentRoute()->computedMiddleware)) { return response()->json(['error' => 'Unauthenticated.'], 401); } -  paing 在20:18 1月27日'18                                     
  • 5.7版中不存在kernal.php中未经身份验证的功能。 –  UJ印度'18 Nov 15'13:01                                     
  • 非常感谢,但是我必须交换线路响应并彼此重定向,因为我有一个api,其中有一个注销方法,所以在邮递员中,当我填写标题值(如授权)后注销用户时, =承载加上登录生成的访问令牌,第一次命中它注销了用户,但是如果我再次单击,它说没有消息,现在被json消息替换:未经身份 验证 –  shashi verma 18年11月20日,5:14                                    
添加评论                    
           
       
20                        

这是我解决的方法。在渲染函数中,我捕获了异常类。如果是Authentication异常类,我会写我的代码以进行重定向(我会在以前版本的未经身份验证的函数中编写的代码)。                        

public function render($request, Exception $exception)
{
    $class = get_class($exception);

    switch($class) {
        case 'Illuminate\Auth\AuthenticationException':
            $guard = array_get($exception->guards(), 0);
            switch ($guard) {
                case 'admin':
                    $login = 'admin.login';
                    break;
                default:
                    $login = 'login';
                    break;
            }

            return redirect()->route($login);
    }

    return parent::render($request, $exception);
}
                   

               
  • 2                                    
    谢谢它为我工作。我在youtube中使用了DevMarketer MultiAuth教程,但似乎在laravel 5.5中不起作用。这解决了我的问题。 –  小熊damayo 17年9月10日在7:02                                    
  • 与我2一起工作,我在起诉devMarketer ...世界太小了 –  Kareem Nour Emam 's Nov 11 '17 at 0:31                                    
  • 在同一个问题上工作。当您开始使用此功能时,是否使用了库存的Laravel 5.5功能unauthenticated还是您还包括unauthenticated5.4 中的功能版本 – cmpreshn 18年  7月4日在1:44                                    
  • 尝试过此代码,但$exception->guards()始终不为我返回任何内容,因此我没有要测试的内容。如果您有其他资源可以建议解决方案,我们将不胜感激。感谢您的回答。 – cmpreshn 18年  7月4日在1:55                                    
  • 非常感谢..太棒了 –  Anand Mainali 1月21日在8:56                                    
再显示1条评论                    
       
5                        

但是在Laravel 5.5中,此位置已移至该位置vendor / laravel / framework / src / Illuminate / Foundation / Exceptions / Handler.php,所以现在如何更改它?我不想更改供应商目录中的内容,以防它被作曲家更新所覆盖。                            

我们只需要使用Illuminate \ Auth \ AuthenticationException即可;                        

然后像laravel 5.4一样工作                        


               
添加评论                    
       
2                        

标准异常处理程序使用命名路由。                        

因此,您只需定义使用该名称的路线即可。                        

因此,在routes/web.php文件中,只需添加以下行:                        

Route::get('mylogin', 'MyLoginController@showLoginForm')->name('login');
                       

name('login')位为该路由命名,因此未经身份验证的异常将使用此路由。                        

您无需费心制作自己的异常处理程序或修改标准异常处理程序。                        

vendor/laravel/framework/src/Illuminate/Routing/Router.phpauth()函数中的文件中找到样板“ auth”代码使用的命名路由(登录,注销,注册,password.request,password.email和password.reset)。使用Route::auth();路由文件中行时,将添加这些路由                        

分享改善这个答案                            
18年9月22日于20:04编辑                                
                                   
                               
布恩                                    
2,2332金徽章25银徽章40铜牌                                    
18年2月4日在23:20 回答                                
                                   
                               
掌上电脑                                    
5723银徽章9枚青铜徽章                                    
  • 感谢为问题提供一个简单的解决方案,我不知道为什么没有其他人对此表示支持,这为我解决了这个问题,而复杂的答案实际上根本没有用。 –  Ashley Kleynhans 18年6月26日在20:57                                    
  • 极大地 帮助了我 –  kellymandem '18 Sep 26'8 :27                                    
添加评论                    
       
0                        

只需在路由文件中添加用于登录的路由即可:                        

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

               
添加评论                    
       
-1                        

除了之外overriding,您还可以直接对位于处的未经身份验证Handler.php的现有功能进行更改,根据防护重定向到预期的路由。vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php                        

/**
 * Convert an authentication exception into a response.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Illuminate\Auth\AuthenticationException  $exception
 * @return \Illuminate\Http\Response
 */
protected function unauthenticated($request, AuthenticationException $exception)
{


    $guard = array_get($exception->guards(),0);
    switch ($guard) {
        case 'admin':
            return $request->expectsJson()
                        ? response()->json(['message' => $exception->getMessage()], 401)
                        : redirect()->guest(route('admin.login'));
            break;

        default:
            return $request->expectsJson()
                        ? response()->json(['message' => $exception->getMessage()], 401)
                        : redirect()->guest(route('login'));
            break;
    }
}
                   

               
  • 我正在使用多重身份验证系统,并且一直在尝试使它正常工作,但是当抛出此异常时,$exception->guards()对我来说却是空的。您是否知道没有警卫的任何原因?我正在Laravel 5.5.40中工作,并且一直在尝试实现用于对不同用户进行身份验证的多个防护措施。我正在研究devmarketer的“ Multi-Auth”视频系列。 – cmpreshn 18年  7月4日在1:40                                     
  • 直接在供应商文件夹中进行更改是非常糟糕的做法!您永远都不要这样做 –  Shehzad 1月7日6:46                                    
添加评论                    
       
-1                        

将您的app \ Exceptions \ Handler.php代码替换为以下内容。...                        

<?php

namespace App\Exceptions;

use Exception;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that are not reported.
     *
     * @var array
     */
    protected $dontReport = [
        //
    ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array
     */
    protected $dontFlash = [
        'password',
        'password_confirmation',
    ];

    /**
     * Report or log an exception.`enter code here`
     *
     * @param  \Exception  $exception
     * @return void
     */
    public function report(Exception $exception)
    {
        parent::report($exception);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Exception  $exception
     * @return \Illuminate\Http\Response
     */
    public function render($request, Exception $exception)
    {
        return parent::render($request, $exception);
    }

    protected function unauthenticated($request, AuthenticationException $exception)
    {
        if ($request->expectsJson()) {
            return response()->json(['message' => $exception->getMessage()], 401);
        }


        $guard = array_get($exception->guards(),0);
        switch ($guard) {
            case 'admin':
                $login = 'admin.login';
                break;

            default:
                $login = 'login';
                break;
        }

        return redirect()->guest(route($login));
    }
}
                   

               
添加评论                    
       
-14                        

1.转到vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php文件。                        

2.搜索方法名称为unauthenticated                        

3.然后将重定向网址从更改 redirect()->guest(route('login'))redirect()->guest(route('api/login')) //whatever you want                        

如果响应是API服务,则可以将响应作为JSON返回。                        


               
  • 4                                    
    从外部软件包更改文件是非常不好的做法!不要这样 – thephper 181月5日,14:  38                                    
  • 1个                                    
    在@thephper的答案中表达:如果您对外部软件包进行更改,则如果更新它们,它们将丢失。 –  SLow Loris 18年4月16日在13:03                                    
  • 如果您想通过运行composer update命令丢失所有代码,请使用此功能! – Erfun 18年  7月24日在17:34                                    
  • 如果您正在运行composer update命令,则没有任何影响。在laravel中,他们在访问API或Routes服务时具有一定级别的安全性。 –  Nadimuthu Sarangapani 18年7月25日在18:04                                    
  • medium.com/@shyammakwana/... -  12月24日在'18 5点35分                                    
再显示2条评论                    
       

来自   https://stackoverflow.com/questions/45340855/laravel-5-5-change-unauthenticated-login-redirect-url            


Asked 
Active 1 year, 1 month ago    
Viewed 30k times
           
34

In Laravel < 5.5 I could change this file app/Exceptions/Handler to change the unauthenticated user redirect url:

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

    return redirect()->guest(route('login'));
}
                   

But in Laravel 5.5 this has been moved to this location vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php so how can I change it now? I don't want to change stuff in the vendor directory encase it gets overridden by composer updates.

protected function unauthenticated($request, AuthenticationException $exception)
{
    return $request->expectsJson()
                ? response()->json(['message' => 'Unauthenticated.'], 401)
                : redirect()->guest(route('login'));
}
               
                      
shareimprove this question                            
asked Jul 27 '17 at 3:26                                
                                   
                               
Rob                                    
4,0954 gold badges27 silver badges35 bronze badges                                    
add a comment                
       

8 Answers 

  正确答案       

activeoldestvotes                    
       
58

But in Laravel 5.5 this has been moved to this location vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php so how can I change it now? I don't want to change stuff in the vendor directory encase it gets overridden by composer updates.

It's just the case that the function is not there by default anymore.

You can just override it as you did in 5.4. Just make sure to include

use Exception;
use Request;
use Illuminate\Auth\AuthenticationException;
use Response;
                       

in the Handler file.

For Example my app/Exceptions/Handler.php looks somewhat like this:

<?php
    namespace App\Exceptions;
    use Exception;
    use Request;
    use Illuminate\Auth\AuthenticationException;
    use Response;
    use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
    class Handler extends ExceptionHandler
    {
        (...) // The dfault file content
        /**
         * Convert an authentication exception into a response.
         *
         * @param  \Illuminate\Http\Request  $request
         * @param  \Illuminate\Auth\AuthenticationException  $exception
         * @return \Illuminate\Http\Response
         */
         protected function unauthenticated($request, AuthenticationException $exception)
         {
            return $request->expectsJson()
                    ? response()->json(['message' => 'Unauthenticated.'], 401)
                    : redirect()->guest(route('authentication.index'));
    }
}
                   
shareimprove this answer                            
edited Sep 1 '17 at 7:38                                
                                   
                               
YakovL                                    
4,07510 gold badges34 silver badges50 bronze badges                                    
answered Sep 1 '17 at 7:10                                
                                   
                               
Seb. Kra.                                    
5964 silver badges3 bronze badges                                    
  • 1                                    
    Best answer I've found, thanks! Just one thing: is there a way instead of using expectsJson(), checking if the request was via the api route? – Dave Nottage Nov 2 '17 at 22:53                                    
  • you are awesome men, i was thinking on disable the web middleware but this solution is best. – Andres Felipe Jan 12 '18 at 13:07                                    
  • 3                                    
    if (in_array('api', \Route::getCurrentRoute()->computedMiddleware)) { return response()->json(['error' => 'Unauthenticated.'], 401); } – paing Jan 27 '18 at 20:18                                     
  • unauthenticated function in kernal.php is not present in version 5.7. – UJ India Nov 15 '18 at 13:01                                     
  • thank you so much, but I had to exchange the line response and redirect with each other, as I am having an api, in which i have a logout method, so in postman when i logged out the user after filling the header value like authorization = bearer plus access token generated by login, on first hit it logged out the user but if i clicked again, it says no message , and now its been replaced by json message : unauthenticated – shashi verma Nov 20 '18 at 5:14                                    
add a comment                    
       
20

Here's how I solved it. In render function I caught exception class. And in case if it's Authentication exception class I wrote my code for redirect (the code I would write in unauthenticated function in previous version).

public function render($request, Exception $exception)
{
    $class = get_class($exception);

    switch($class) {
        case 'Illuminate\Auth\AuthenticationException':
            $guard = array_get($exception->guards(), 0);
            switch ($guard) {
                case 'admin':
                    $login = 'admin.login';
                    break;
                default:
                    $login = 'login';
                    break;
            }

            return redirect()->route($login);
    }

    return parent::render($request, $exception);
}
                   
shareimprove this answer                            
answered Aug 30 '17 at 19:44                                
                                   
                               
Milomir                                    
3091 silver badge4 bronze badges                                    
  • 2                                    
    thanks it worked for me. i used DevMarketer MultiAuth tutorial in youtube but it seems it's not working in laravel 5.5. this solve my problem. – winnie damayo Sep 10 '17 at 7:02                                    
  • worked with me 2, and i am suing devMarketer...world is too small – Kareem Nour Emam Nov 11 '17 at 0:31                                    
  • Working on this same issue. When you got this to work, did you use the stock Laravel 5.5 function for unauthenticated? Or did you also include the version of the unauthenticated function from 5.4? – cmpreshn Jul 4 '18 at 1:44                                    
  • Have tried this code, but $exception->guards() always returns nothing for me, so I have nothing to test against. If you have any additional resources you could recommend for a solution, it would be appreciated. Thanks for your answer. – cmpreshn Jul 4 '18 at 1:55                                    
  • thanks a lot.. works great – Anand Mainali Jan 21 at 8:56                                    
show 1 more comment                    
       
5

But in Laravel 5.5 this has been moved to this location vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php so how can I change it now? I don't want to change stuff in the vendor directory encase it gets overridden by composer updates.

We need to just include the use Illuminate\Auth\AuthenticationException;

and then it works as in laravel 5.4

shareimprove this answer                            
answered Sep 12 '17 at 13:30                                
                                   
                               
LetsCMS Pvt Ltd                                    
4503 silver badges6 bronze badges                                    
  • Thanks, this solution is work for me in Laravel 5.5 :) – Tommy Tom Nov 9 '17 at 2:23                                    
add a comment                    
       
2

The standard exception handler uses a named route.

So, you just define your route to use that name.

So, in your routes/web.php file, just add the line:

Route::get('mylogin', 'MyLoginController@showLoginForm')->name('login');
                       

The name('login') bit gives this route a name, so the unauthenticated exception will use this route.

You don't need to bother messing around making your own exception handler, or modifying the standard exception handler.

The named routes used by the boilerplate 'auth' code can be found in the vendor/laravel/framework/src/Illuminate/Routing/Router.php file, in the auth() function. (login, logout, register, password.request, password.email and password.reset). These routes are added when you use the Route::auth(); line in the route file.

shareimprove this answer                            
edited Sep 22 '18 at 20:04                                
                                   
                               
Brane                                    
2,2332 gold badges25 silver badges40 bronze badges                                    
answered Feb 4 '18 at 23:20                                
                                   
                               
pscs                                    
5723 silver badges9 bronze badges                                    
  • Thanks for a simple solution to the problem, I don't know why nobody else has upvoted this, this solved the issue for me, and the complex answers actually didn't even work at all. – Ashley Kleynhans Jun 26 '18 at 20:57                                    
  • This helped me alot – kellymandem Sep 26 '18 at 8:27                                    
add a comment                    
       
0

Just add a route for login in routes file:

Route::get('/login', [
   'uses' => 'UserController@getSignin',
   'as' => 'login'
]);
                   
shareimprove this answer                            
answered Feb 2 '18 at 12:49                                
                                   
                               
zardox                                    
415 bronze badges                                    
add a comment                    
       
-1

Other than overriding, you could directly make changes in Handler.php to the existing function unauthenticated located at vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php to redirect to intended route based on guards.

/**
 * Convert an authentication exception into a response.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Illuminate\Auth\AuthenticationException  $exception
 * @return \Illuminate\Http\Response
 */
protected function unauthenticated($request, AuthenticationException $exception)
{


    $guard = array_get($exception->guards(),0);
    switch ($guard) {
        case 'admin':
            return $request->expectsJson()
                        ? response()->json(['message' => $exception->getMessage()], 401)
                        : redirect()->guest(route('admin.login'));
            break;

        default:
            return $request->expectsJson()
                        ? response()->json(['message' => $exception->getMessage()], 401)
                        : redirect()->guest(route('login'));
            break;
    }
}
                   
shareimprove this answer                            
edited Jan 29 '18 at 12:32                                
                                   
                               
Linus Unnebäck                                    
9,9115 gold badges46 silver badges61 bronze badges                                    
answered Jan 29 '18 at 11:19                                
                                   
                               
Tekraj Chhetri                                    
352 bronze badges                                    
  • I'm working on a multiple authentication system, and I've been trying to get this to work, but when this exception is thrown, $exception->guards() is coming back as empty for me. Do you know of any reason why the guards would not be available? I'm working in Laravel 5.5.40, and have been trying to implement multiple guards for authenticating different users. I'm working off of the video series on 'Multi-Auth' by devmarketer. – cmpreshn Jul 4 '18 at 1:40                                     
  • making changes in the vendor folder directly is highly bad practice! you should never ever do this – Shehzad Jan 7 at 6:46                                    
add a comment                    
       
-1

Replace Your app\Exceptions\Handler.php code with the following....

<?php

namespace App\Exceptions;

use Exception;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that are not reported.
     *
     * @var array
     */
    protected $dontReport = [
        //
    ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array
     */
    protected $dontFlash = [
        'password',
        'password_confirmation',
    ];

    /**
     * Report or log an exception.`enter code here`
     *
     * @param  \Exception  $exception
     * @return void
     */
    public function report(Exception $exception)
    {
        parent::report($exception);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Exception  $exception
     * @return \Illuminate\Http\Response
     */
    public function render($request, Exception $exception)
    {
        return parent::render($request, $exception);
    }

    protected function unauthenticated($request, AuthenticationException $exception)
    {
        if ($request->expectsJson()) {
            return response()->json(['message' => $exception->getMessage()], 401);
        }


        $guard = array_get($exception->guards(),0);
        switch ($guard) {
            case 'admin':
                $login = 'admin.login';
                break;

            default:
                $login = 'login';
                break;
        }

        return redirect()->guest(route($login));
    }
}
                   
shareimprove this answer                            
answered Jul 28 '18 at 2:56                                
                                   
                               
Waheed Shahzad                                    
1                                    
add a comment                    
       
-14

1.Go to vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php file.

2.Search the method name is unauthenticated.

3.And change the redirect url from redirect()->guest(route('login')) to redirect()->guest(route('api/login')) //whatever you want.

You could return the response as a JSON if it is API services.

shareimprove this answer                            
answered Nov 17 '17 at 20:24                                
                                   
                               
Nadimuthu Sarangapani                                    
831 silver badge3 bronze badges                                    
  • 4                                    
    It is very bad practice to make changes in files from external packages! Don't do this. – thephper Jan 5 '18 at 14:38                                    
  • 1                                    
    to ellaborate on @thephper's answer: if you make changes to external packages they will be lost if you ever update them. – SLow Loris Apr 16 '18 at 13:03                                    
  • If you want to lose all of your code by running a composer update command, use this!! – Erfun Jul 24 '18 at 17:34                                    
  • Nothing will impact if you are running the composer update command. In laravel, they are having certain level of security while accessing the API or Routes services. – Nadimuthu Sarangapani Jul 25 '18 at 18:04                                    
  • medium.com/@shyammakwana/… – San Dec 24 '18 at 5:35                                    
show 2 more comments                    
       

来自   https://stackoverflow.com/questions/45340855/laravel-5-5-change-unauthenticated-login-redirect-url            


           


           


           

如何更改Laravel 5 Auth过滤器的默认重定向URL?                

问问题                
 
活动时间 1年,8个月前                
观看了 60k次                
                       
19                                

默认情况下,如果我没有登录,请尝试在浏览器中访问:                                

http://localhost:8000/home
                               

它重定向到 http://localhost:8000/auth/login                                

如何更改以将我重定向到 http://localhost:8000/login                                

                                 
分享改善这个问题                                        
17年5月11日于21:50编辑                                            
                                               
                                           
杰夫·普基特                                                
20.1千11金徽章71银徽章121青铜徽章                                                
2015年2月24日在17:29 问                                            
                                               
                                           
弗拉基米尔                                                
1,2515金徽章18银徽章33枚青铜徽章                                                
添加评论                            
                   

10个答案                            

活跃的最古老的选票                                
                   
41                                    

我想在Laravel 5.5中做同样的事情。处理身份验证已向Illuminate\Auth\Middleware\Authenticate抛出Illuminate\Auth\AuthenticationException                                    

已处理了该异常Illuminate\Foundation\Exceptions\Hander.php,但您不想更改原始供应商文件,因此可以通过将其添加到来用您自己的项目文件覆盖它App\Exceptions\Handler.php                                    

为此,将以下内容添加到Handler的顶部App\Exceptions\Handler.php                                    

use Illuminate\Auth\AuthenticationException;
                                   

然后添加以下方法,必要时进行编辑:                                    

/**
 * Convert an authentication exception into an unauthenticated response.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Illuminate\Auth\AuthenticationException  $exception
 * @return \Illuminate\Http\Response
 */
protected function unauthenticated($request, AuthenticationException $exception)
{
    if ($request->expectsJson()) {
        return response()->json(['error' => 'Unauthenticated.'], 401);
    }

    return redirect()->guest('login'); //<----- Change this
}
                                   

只需更改return redirect()->guest('login');return redirect()->guest(route('auth.login'));或其他。                                    

我想写下来,因为我花了超过5分钟的时间才弄清楚。如果您碰巧在文档中找到此行,请给我一行,因为我找不到。                                    

分享改善这个答案                                        
18年1月29日于12:33编辑                                            
                                               
                                           
查克·勒·巴特                                                
39.3千47金币159银徽章241青铜徽章                                                
2016年9月19日在10:53回答                                            
                                               
                                           
莫里兹·埃韦特                                                
5827银徽章14枚青铜徽章                                                
  • 7                                                
    5分钟?...花花公子...对我而言,一切至少需要1个小时。 –法 16年  12月11日在23:17                                                
  • 2                                                
    不要更改核心文件,这是一个非常糟糕的主意,当作曲家运行更新时,所有更改都将被覆盖 – twigg 17年  1月10日,15:34                                                
  • 1个                                                
    可怕的答案。+1 –  Awais Usmani 17年1月24日在16:35                                                
  • 2                                                
    @twigg不是核心文件。这是位于App \ Exceptions \ Handler中的例外处理程序。什么都不会被覆盖 –  Moritz Ewert 17年8月8日在13:51                                                
  • 1个                                                
    @Inigo guest方法在重定向未经身份验证的用户时将当前URL保存为“预期”目标。登录后,用户将返回到预期的网址 –  Moritz Ewert 17年9月9日,12:59                                                
再显示3条评论                                
                   
31                                    

只是为了扩展@ultimate的答案:                                    

  1. 您需要修改App\Http\Middleware\Authenticate::handle()方法并更改auth/login/login

  2. 比您需要$loginPath\App\Http\Controllers\Auth\AuthController类中添加属性为什么?参见Laravel来源

结果,您将在中间件中包含以下内容:                                    

namespace App\Http\Middleware;
class Authenticate {
        /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if ($this->auth->guest())
        {
            if ($request->ajax())
            {
                return response('Unauthorized.', 401);
            }
            else
            {
                return redirect()->guest('/login'); // <--- note this
            }
        }

        return $next($request);
    }
}
                                   

而这在您的AuthController中:                                    

namespace App\Http\Controllers\Auth;
class AuthController extends Controller
{
    protected $loginPath = '/login'; // <--- note this

    // ... other properties, constructor, traits, etc 
}
                               
分享改善这个答案                                        
15年3月2日于9:29编辑                                            
15年3月2日在9:18 回答                                            
                                               
                                           
e1v                                                
5383银徽章5枚青铜徽章                                                
添加评论                                
                   
11                                    

这是Laravel 5.4解决方案:                                    

app / Exceptions / Handler.php中有一个新的unauthenticated()方法,该方法处理未经身份验证的用户并重定向到登录路径。                                    

所以改变                                    

return redirect()->guest('login');
                                   

                                   

return redirect()->guest('auth/login');
                               

                           
  • 嗨@salil我有错误对不起,找不到您要查找的页面。RouteCollection.php第161行中的NotFoundHttpException:加载自定义登录URL时。我可以知道如何解决这个问题吗?我是否需要为自定义登录创建新视图? –  davidlee'4 Apr 3'在10:19                                                
  • 1个                                                
    基督骑着自行车,这在Laravel 5.5中再次发生了变化。unauthenticated()现在,方法已从App / Exceptions / Handler.php中删除。就像他们想要进一步混淆身份验证系统内部工作的每个版本一样。对于那些想要修改甚至是理解的人来说,这非常令人沮丧。 – Inigo 17年  10月16日在12:08                                                 
  • 好的,这里的Laravel 5.5解决方案是:stackoverflow.com/questions/45340855/…– Inigo, 17 年  10月16日,12:13                                                
添加评论                                
                   
5                                    

在Laravel 5.6中,转到app / Exceptions文件夹并打开Handler.php,添加一个新方法来覆盖未经身份验证的方法,如下所示:                                    

protected function unauthenticated($request, AuthenticationException $exception)
{
    if($request->ajax())
    {
        return response([
            "message" => "Unauthenticated.",
            "data" => [],
        ],401);
    }

    return redirect()->to('/');
}
                                   

当您使用内置的“ auth”中间件访问受保护的路由时,将触发此方法。现在,您将完全控制重定向到何处或发送了响应。                                    


                           
添加评论                                
                   
4                                    

使用Laravel 5中的中间件进行身份验证检查。                                    

而auth的中间件是App\Http\Middleware\Authenticate                                    

因此,您可以handle使用中间件的方法进行更改                                    


                           
添加评论                                
                   
3                                    

编辑:在Laravel 5.1上,只需添加受保护的$ redirectPath ='/ url / you / want'; 到AuthController就能解决问题。                                    

参考:http : //laravel.com/docs/5.1/authentication#included-authenticating                                    


在Laravel 5.1上,它已完全移至App \ Http \ Middleware下的另一个名为RedirectIfAuthenticated.php的中间件。                                    

public function handle($request, Closure $next)

{
    if ($this->auth->check()) {
        return redirect('/'); //change this part to anywhere you wish to be redirected to
    }

    return $next($request);
}
                                   

希望能帮助到你。                                    


                           
添加评论                                
                   
1个                                    

你可以请输出php artisan route:list                                    

没错,您可以设置以下属性:                                    

protected $loginPath = 'xxx';

protected $redirectPath = 'xxx';

protected $redirectAfterLogout = 'xxx';
                                   

设置这个属性给你 AuthController.php                                    


                           
添加评论                                
                   
0                                    

由于您的其他问题被标记为重复。.我将在此处尝试回答。                                    

首先,您需要像                                    

<?php
Route::get(config('constants.cms_path') . '/login', [
    'as' => 'login',
    'uses' => 'Auth\AuthController@getLogin'
]);
                                   

在刀片中..确保在“登录网址”链接中使用命名路由,例如                                    

{{ route('login') }}
                                   

在Middleware / Authenticate.php中,将重定向访客更改为                                    

return redirect()->guest(config('constants.cms_path') . '/login');
                               

                           
添加评论                                
                   
0                                    

要在登录后更改重定向,只需转到app / Http / Controllers / Auth / LoginController.php并将其添加到类LoginController中:                                    

protected $redirectTo = '/redirect-url-here';
                                   

新用户注册后的重定向相同,但在这种情况下,在AuthController.php上                                    


                           
添加评论                                
                   
0                                    

对于Laravel 5.4,您可以设置受保护的$ redirectTo ='/'; 在LoginController.php文件中。或者在RegistersUsers.php文件中,您可以                                    

protected function registered(Request $request, $user)
{
    return redirect('tosomeRoute'); 
    //Note: This code will run when
    //The user has been registered
}
                               

                           
添加评论                                
                   

 来自  https://stackoverflow.com/questions/28702372/how-to-change-default-redirect-url-of-laravel-5-auth-filter                        


           

Asked 
Active 1 year, 8 months ago            
Viewed 60k times
                   
19

By default if I am not logged and I try visit this in browser:

http://localhost:8000/home
                           

It redirect me to http://localhost:8000/auth/login                            

How can I change to redirect me to http://localhost:8000/login                            

                             
shareimprove this question                                    
edited May 11 '17 at 21:50                                        
                                           
                                       
Jeff Puckett                                            
20.1k11 gold badges71 silver badges121 bronze badges                                            
asked Feb 24 '15 at 17:29                                        
                                           
                                       
Vladimir                                            
1,2515 gold badges18 silver badges33 bronze badges                                            
add a comment                        
               

10 Answers

activeoldestvotes                            
               
41

I wanted to do the same thing in Laravel 5.5. Handling authentication has moved to Illuminate\Auth\Middleware\Authenticate which throws an Illuminate\Auth\AuthenticationException.

That exception is handled in Illuminate\Foundation\Exceptions\Hander.php, but you don't want to change the original vendor files, so you can overwrite it with your own project files by adding it to App\Exceptions\Handler.php.

To do this, add the following to the top of the Handler class in App\Exceptions\Handler.php:

use Illuminate\Auth\AuthenticationException;
                               

And then add the following method, editing as necessary:

/**
 * Convert an authentication exception into an unauthenticated response.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Illuminate\Auth\AuthenticationException  $exception
 * @return \Illuminate\Http\Response
 */
protected function unauthenticated($request, AuthenticationException $exception)
{
    if ($request->expectsJson()) {
        return response()->json(['error' => 'Unauthenticated.'], 401);
    }

    return redirect()->guest('login'); //<----- Change this
}
                               

Just change return redirect()->guest('login'); to return redirect()->guest(route('auth.login')); or anything else.

I wanted to write this down because it took me more than 5 minutes to figure it out. Please drop me a line if you happened to find this in the docs because I couldn't.

shareimprove this answer                                    
edited Jan 29 '18 at 12:33                                        
                                           
                                       
Chuck Le Butt                                            
39.3k47 gold badges159 silver badges241 bronze badges                                            
answered Sep 19 '16 at 10:53                                        
                                           
                                       
Moritz Ewert                                            
5827 silver badges14 bronze badges                                            
  • 7                                            
    5 minutes? ...dude... everything will be at least 1 hour for me lol. – Fahmi Dec 11 '16 at 23:17                                            
  • 2                                            
    Do not change core files, this is a really bad idea and when composer runs an update all your changes will be over written – twigg Jan 10 '17 at 15:34                                            
  • 1                                            
    Awsome answer . +1 – Awais Usmani Jan 24 '17 at 16:35                                            
  • 2                                            
    @twigg that's no core file. This is the exeption handler located at App\Exceptions\Handler. Nothing will be overwritten – Moritz Ewert Mar 8 '17 at 13:51                                            
  • 1                                            
    @Inigo the guest method saves the current url as the 'intended' destination while it redirects unauthenticated users. after logging in the user will be returned to the intended url – Moritz Ewert Oct 9 '17 at 12:59                                            
show 3 more comments                            
               
31

Just to extend @ultimate's answer:

  1. You need to modify App\Http\Middleware\Authenticate::handle() method and change auth/login to /login.

  2. Than you need to add $loginPath property to your \App\Http\Controllers\Auth\AuthController class. Why? See Laravel source.

In result you'll have this in your middleware:

namespace App\Http\Middleware;
class Authenticate {
        /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if ($this->auth->guest())
        {
            if ($request->ajax())
            {
                return response('Unauthorized.', 401);
            }
            else
            {
                return redirect()->guest('/login'); // <--- note this
            }
        }

        return $next($request);
    }
}
                               

And this in your AuthController:

namespace App\Http\Controllers\Auth;
class AuthController extends Controller
{
    protected $loginPath = '/login'; // <--- note this

    // ... other properties, constructor, traits, etc 
}
                           
shareimprove this answer                                    
edited Mar 2 '15 at 9:29                                        
answered Mar 2 '15 at 9:18                                        
                                           
                                       
e1v                                            
5383 silver badges5 bronze badges                                            
add a comment                            
               
11

This is Laravel 5.4 Solution:                                

There is a new unauthenticated() method in app/Exceptions/Handler.php which handles unauthenticated users and redirects to login path.

So change

return redirect()->guest('login');
                               

to

return redirect()->guest('auth/login');
                           
shareimprove this answer                                    
answered Feb 21 '17 at 15:58                                        
                                           
                                       
Salil Kothadia                                            
1412 silver badges3 bronze badges                                            
  • Hi @salil i have error Sorry, the page you are looking for could not be found. NotFoundHttpException in RouteCollection.php line 161: when loading the custom login url. May i know how to solve this issue? do i need to create a new view just for the custom login? – davidlee Apr 3 '17 at 10:19                                            
  • 1                                            
    Christ on a bike, this has changed yet again in Laravel 5.5. The unauthenticated() method is now removed from App/Exceptions/Handler.php. It's like with every version they want to obfuscate the inner workings of the authentication system further. Very frustrating for those of us wanting to modify- or even just understand- it. – Inigo Oct 16 '17 at 12:08                                             
  • OK, Laravel 5.5 solution here: stackoverflow.com/questions/45340855/… – Inigo Oct 16 '17 at 12:13                                            
add a comment                            
               
5

In Laravel 5.6, go to app/Exceptions folder and open the Handler.php, add a new method that overrides the unauthenticated method like so:

protected function unauthenticated($request, AuthenticationException $exception)
{
    if($request->ajax())
    {
        return response([
            "message" => "Unauthenticated.",
            "data" => [],
        ],401);
    }

    return redirect()->to('/');
}
                               

This method is triggered when you access a protected route using the built-in "auth" middleware. Now you will have full control where to redirect or the response sent.

shareimprove this answer                                    
answered Mar 11 '18 at 8:13                                        
                                           
                                       
Darryldecode                                            
5335 silver badges10 bronze badges                                            
add a comment                            
               
4

Authentication checks are made using middleware in Laravel 5.

And the middleware for auth is App\Http\Middleware\Authenticate.

So, you can change it in handle method of the middleware.

shareimprove this answer                                    
answered Feb 24 '15 at 18:03                                        
                                           
                                       
ultimate                                            
6188 silver badges17 bronze badges                                            
add a comment                            
               
3

EDIT: On Laravel 5.1, simply add protected $redirectPath = '/url/you/want'; to AuthController would do the trick.

REFER : http://laravel.com/docs/5.1/authentication#included-authenticating                                


On Laravel 5.1, it is completely moved to another middleware named RedirectIfAuthenticated.php under App\Http\Middleware                                

public function handle($request, Closure $next)

{
    if ($this->auth->check()) {
        return redirect('/'); //change this part to anywhere you wish to be redirected to
    }

    return $next($request);
}
                               

Hope it helps.


                                   
add a comment                            
               
1

could you please outputs php artisan route:list please

You are right you can set the following attributes:

protected $loginPath = 'xxx';

protected $redirectPath = 'xxx';

protected $redirectAfterLogout = 'xxx';
                               

Set this attribute to you AuthController.php                                


                                   
add a comment                            
               
0

Since your other question was marked as duplicate..I will try to answer it here..

First you need to change your route like

<?php
Route::get(config('constants.cms_path') . '/login', [
    'as' => 'login',
    'uses' => 'Auth\AuthController@getLogin'
]);
                               

In your blade..make sure you use named route in the Login url link like

{{ route('login') }}
                               

In Middleware/Authenticate.php change the redirect guest to

return redirect()->guest(config('constants.cms_path') . '/login');
                           

                                   
add a comment                            
               
0

To change the redirection after the login, you only have to go to app/Http/Controllers/Auth/LoginController.php and add that inside the class LoginController:

protected $redirectTo = '/redirect-url-here';
                               

Same for redirection after a new users register, but in that case, on AuthController.php


                                   
add a comment                            
               
0

For Laravel 5.4 You can set protected $redirectTo = '/'; in LoginController.php FILE. Or in RegistersUsers.php file you can

protected function registered(Request $request, $user)
{
    return redirect('tosomeRoute'); 
    //Note: This code will run when
    //The user has been registered
}
                           

                                   
add a comment                            
               

 来自  https://stackoverflow.com/questions/28702372/how-to-change-default-redirect-url-of-laravel-5-auth-filter                    


           
       


           


           


           


           


           


普通分类: