主要目的就是结合中间件,如果用户没有登录打开后台,实现跳转到指定页面。
1: php artisan make:middleware AdminLogin
这样Http下面的Middleware会生成AdmnLogin.php
2:里面写handle方法如下,这个结合自己的写,指定跳转到页面
3:在Http下面的Kernel.php里的protected $routeMiddleware加上路由中间件
个人分类: Laraver欢迎各位兄弟 发布技术文章
这里的技术是共享的
主要目的就是结合中间件,如果用户没有登录打开后台,实现跳转到指定页面。
1: php artisan make:middleware AdminLogin
这样Http下面的Middleware会生成AdmnLogin.php
2:里面写handle方法如下,这个结合自己的写,指定跳转到页面
3:在Http下面的Kernel.php里的protected $routeMiddleware加上路由中间件
个人分类: Laraver来自 https://blog.csdn.net/myarche/article/details/79738417
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'));
}
但是在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'));
}
}
if (in_array('api', \Route::getCurrentRoute()->computedMiddleware)) { return response()->json(['error' => 'Unauthenticated.'], 401); } - paing 在20:18 1月27日'18
这是我解决的方法。在渲染函数中,我捕获了异常类。如果是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);
}
但是在Laravel 5.5中,此位置已移至该位置vendor / laravel / framework / src / Illuminate / Foundation / Exceptions / Handler.php,所以现在如何更改它?我不想更改供应商目录中的内容,以防它被作曲家更新所覆盖。
我们只需要使用Illuminate \ Auth \ AuthenticationException即可;
然后像laravel 5.4一样工作
标准异常处理程序使用命名路由。
因此,您只需定义使用该名称的路线即可。
因此,在routes/web.php文件中,只需添加以下行:
Route::get('mylogin', 'MyLoginController@showLoginForm')->name('login');
该name('login')位为该路由命名,因此未经身份验证的异常将使用此路由。
您无需费心制作自己的异常处理程序或修改标准异常处理程序。
可vendor/laravel/framework/src/Illuminate/Routing/Router.php在auth()函数中的文件中找到样板“ auth”代码使用的命名路由。(登录,注销,注册,password.request,password.email和password.reset)。使用Route::auth();路由文件中的行时,将添加这些路由。
只需在路由文件中添加用于登录的路由即可:
Route::get('/login', [
'uses' => 'UserController@getSignin',
'as' => 'login'
]);
除了之外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;
}
}
将您的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));
}
}
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返回。
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'));
}
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'));
}
}
if (in_array('api', \Route::getCurrentRoute()->computedMiddleware)) { return response()->json(['error' => 'Unauthenticated.'], 401); } – paing Jan 27 '18 at 20:18
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);
}
unauthenticated? Or did you also include the version of the unauthenticated function from 5.4? – cmpreshn Jul 4 '18 at 1:44
$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
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
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.
Just add a route for login in routes file:
Route::get('/login', [
'uses' => 'UserController@getSignin',
'as' => 'login'
]);
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;
}
}
$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
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));
}
}
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.
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
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.
Just to extend @ultimate's answer:
You need to modify App\Http\Middleware\Authenticate::handle() method and change auth/login to /login.
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
}
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');
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
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.
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.
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.
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
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');
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
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
}