Laravel 5.3 Unauthorized User Redirection Policy

I can not find it in the documentation. How to redirect an unauthorized user?

RolePolicy.php

class RolePolicy { use HandlesAuthorization; public function manageRoles(User $user) { return $user->isAdmin(); } } 

RolesController.php

 function __construct() { $this->authorize('manageRoles', Role::class); } 

Thanks in advance

+9
source share
3 answers

You can change the file app\Exceptions\Handler.php

on the render function:

 public function render($request, Exception $e) { /**modified part**/ if ($request->wantsJson()) { return response([ 'success' => false, 'message' => $e->getMessage() ], 404); } if ($e instanceof AuthorizationException) { return redirect('path'); //or simply return view('errors.forbidden'); //but this will return an OK, 200 response. } /**end of modified part**/ return parent::render($request, $e); } 

If you want to put 403, use the response() helper function. You can see the documentation for the answers here https://laravel.com/docs/master/responses

Basically, you can use the solution to play with a lot of options. But the easiest way is to simply create a view file: errors/403.blade.php and this view will automatically load when you click unauthorized exceptions. The same will work for 404 not found, just create 404.blade.php .

+8
source

As far as I know, in Laravel 5.3 it's not like in any version of Laravel 5.

There is a route middleware called auth that references App\Http\Middleware\Authenticate (defined in app / http / Kernel.php)

In this class:

 public function handle($request, Closure $next, $guard = null) { if (Auth::guard($guard)->guest()) { if ($request->ajax()) { return response('Unauthorized.', 401); } else { return redirect()->guest('login'); } } return $next($request); } 

This auth middleware can be applied to routes requiring authentication.

More details about middleware here: https://laravel.com/docs/5.3/middleware

More about authentication here: https://laravel.com/docs/5.3/authentication

+2
source

Use Laravel Gates, in your controller methods. For instance:

 public function update(Role $role){ if(\Gates::allows('manageRoles',$role)) { return redirect()->back()->with('status','Success'); } 

However, I personally find it too problematic to set a redirect page for each controller action. If the action is rejected because the user was manipulating the URL, and not because some preconditions were not met, then the 404th page with the home button is enough.

As in the answer above, it is much simpler and easier to use the Laravel answers, call up the desired error page and send a custom message.

like this answer from another topic:

 return response("User can't perform this action.", 401); 

fooobar.com/questions/2348355 / ...

0
source

All Articles