php Laravel 5.5 更改未经身份验证的登录重定向 url

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45340855/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 03:06:36  来源:igfitidea点击:

Laravel 5.5 change unauthenticated login redirect url

phplaravelauthentication

提问by Rob

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

Laravel < 5.5我可以更改此文件app/Exceptions/Handler以更改未经身份验证的用户重定向 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.5this has been moved to this location vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.phpso how can I change it now? I don't want to change stuff in the vendor directory encase it gets overridden by composer updates.

但是 in Laravel 5.5this 已经移到这个位置了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'));
}

回答by Seb. Kra.

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.

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

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

您可以像在 5.4 中那样覆盖它。只要确保包括

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

in the Handler file.

在处理程序文件中。

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

例如我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'));
    }
}

回答by Milomir

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);
}

回答by LetsCMS Pvt Ltd

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.

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

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

我们只需要包含 use Illuminate\Auth\AuthenticationException;

and then it works as in laravel 5.4

然后它就像在laravel 5.4中一样工作

回答by pscs

The standard exception handler uses a named route.

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

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

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

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

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

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

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

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

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.phpfile, 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.

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

回答by zardox

Just add a route for login in routes file:

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

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

回答by edwin ndeere

Copy this to your app\Exception\Handler

Copy this to your app\Exception\Handler

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

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':
        return redirect()->guest(route('admin.login'));
       break;

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

回答by Fahri Meral

For Laravel 7.x+

对于 Laravel 7.x+

===========**top add class:**================
use Illuminate\Auth\AuthenticationException;

use Illuminate\Support\Arr;
=======================================

public function render($request, Throwable $exception)
    {
        if($exception instanceof AuthenticationException){
            $guard = Arr::get($exception->guards(), 0);
            switch($guard){
                case 'admin':
                    return redirect(route('admin.login'));
                    break;
                default:
                    return redirect(route('login'));
                    break;
            }
        }

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

回答by Deekep Thapa

For Laravel verison 7.*

对于 Laravel 版本 7.*

File: App\Exceptions\Handler.php

文件:App\Exceptions\Handler.php

use Illuminate\Support\Arr; //Top Class

使用 Illuminate\Support\Arr; //顶级

use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;

使用 Illuminate\Foundation\Exceptions\Handler 作为 ExceptionHandler;

public function render($request, Throwable $exception) {

公共函数渲染($request,Throwable $exception){

    // for Multi AUth guard

    if($exception instanceof AuthenticationException){
        $guard = Arr::get($exception->guards(), 0);
        switch($guard){
            case 'admin':
                return redirect(route('admin.login'));
                break;
            default:
                return redirect(route('login'));
                break;
        }
    }



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

回答by Tekraj Chhetri

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

除此之外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;
    }
}

回答by Waheed Shahzad

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

将您的 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));
    }
}