Laravel 5.5 - After upgrading auth is not redirecting properly - authentication

I just upgraded my application from Laravel 5.4 to v 5.5. Non authenticated users are not redirecting properly now.
Normally a non authenticated user should be redirected to /manage/login but it is redirected to /login route.
Everything was working perfect in Laravel v 5.4
My app contain two guards.
Routing in web.php
Auth::routes();
Route::middleware(['auth:manager'])->group(function () {
Route::get('/manage', 'Manage\AdminController#dashboard')->name('manage.home');
});
So before upgrade a non authenticated user trying to access /manage was redirected to /manage/login but after upgrading it is redirecting to /login.
I have Auth Controllers copied and modified as needed in Manage\Auth.
Similarly Views are in folder structure Manage\Auth.
My LoginController in Controllers\Manage\Auth
|
Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo = '/manage/';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
public function showLoginForm()
{
return view('manage.auth.login');
}
public function logout(Request $request)
{
$this->guard()->logout();
$request->session()->flush();
$request->session()->regenerate();
return redirect('/manage');
}
protected function guard()
{
return Auth::guard('manager');
}

I faced the same problem, and it's quit simple to solve.
the point is that if you are using guards you were probably handling unauthenticated exception in your app/Exceptions/Handler.php . when using laravel 5.4 .
After update to 5.5 this is done under vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php .
You should refer to this Laravel 5.5 change unauthenticated login redirect url for more details about how to solve it.

Related

Custom login and logout response in Laravel 7.x

I am trying to login and logout from a create-react-app application which uses an application with Laravel 7.x as backend. Where can I put the custom response message for /login and /logout auth routes in Laravel 7.x. I used the artisan command for auth scaffolding.
I know about Single Page Application authentication in Laravel. It is given in the Laravel Sanctum page. https://laravel.com/docs/7.x/sanctum. I have followed everything there and have no problems with that.
I get redirected to /home route even when I have commented out the line in LoginController.php
protected $redirectTo = RouteServiceProvider::HOME;
I tried to look up the documentation https://laravel.com/docs/7.x/authentication it says "Laravel provides an empty authenticated(Request $request, $user) method that may be overwritten if desired:". But don't know where this method can be written.
So I will answer my own question. This method is present in the trait AuthenticatesUsers.php which is present in vendor/laravel/ui/auth-backend/ directory.
I added this in the empty method called authenticated() in AuthenticateUsers.php trait present in above link.
/**
* The user has been authenticated.
*
* #param \Illuminate\Http\Request $request
* #param mixed $user
* #return mixed
*/
protected function authenticated(Request $request, $user)
{
return new Response(['success' => 'you have been authenticated'], 200);
}
For custom logout response, use the loggedOut() method in AuthenticatesUsers.php trait.
Hope this helps someone. I also created a pull request in the docs repository, hope it gets accepted. Thanks.

Authenticated method in Laravel 6

I'm using Laravel 6. I want to generate a new API token for the user each time the user logged in.
Referring to some answers on StackOverflow, there is a method authenticated in LoginController which is been called just after the user is logged in successfully. I cannot find the authenticated method in Laravel 6.
Is there a new way to achieve the same thing in Laravel 6?
As per Laravel Documentation:
If you need more robust customization of the response returned when a
user is authenticated, Laravel provides an empty authenticated(Request
$request, $user) method that may be overwritten if desired:
/**
* The user has been authenticated.
*
* #param \Illuminate\Http\Request $request
* #param mixed $user
* #return mixed
*/
protected function authenticated(Request $request, $user)
{
return response([
//
]);
}
Just place the following method inside app\Http\Controllers\LoginController (overriding it):
use Illuminate\Http\Request;
protected function authenticated(Request $request, $user)
{
// stuff to do after user logs in
return redirect()->intended($this->redirectPath());
}
Reference:
Laravel -> Authentication -> Authenticating

How to prevent user login automatically after registration in Laravel 5.5

Im using laravel 5.5 and the auth module that provides login and registration modules automatically.
But when i register a new user, it automatically logs in the user and shows the home page.
I dont want to login the user. How do i prevent this ?
You need to overwrite the register() function in /app/Http/Controllers/Auth/RegisterController.php file
This is the original function:
public function register(Request $request)
{
$this->validator($request->all())->validate();
event(new Registered($user = $this->create($request->all())));
$this->guard()->login($user); // this line logs in the user
return $this->registered($request, $user)
?: redirect($this->redirectPath());
}
and you need to copy this function into RegisterController.php and customize it however you want.

How do i change the view path for make:auth controllers in laravel?

How do I change the routes of the authentication components which are created with make:auth?
routes/web.php contains
Auth::routes();
How do I change the path for register, for example, to /account ?
Laravel's Auth::routes(); uses a function auth() defined in vendor/laravel/framework/src/Illuminate/Routing/Router.php
You can copy the content of this function and paste it directly in your web.php file and update as you want.
public function auth()
{
// Authentication Routes...
$this->get('login', 'Auth\LoginController#showLoginForm')->name('login');
$this->post('login', 'Auth\LoginController#login');
$this->post('logout', 'Auth\LoginController#logout')->name('logout');
// Registration Routes...
$this->get('register', 'Auth\RegisterController#showRegistrationForm')->name('register');
$this->post('register', 'Auth\RegisterController#register');
// Password Reset Routes...
$this->get('password/reset', 'Auth\ForgotPasswordController#showLinkRequestForm')->name('password.request');
$this->post('password/email', 'Auth\ForgotPasswordController#sendResetLinkEmail')->name('password.email');
$this->get('password/reset/{token}', 'Auth\ResetPasswordController#showResetForm')->name('password.reset');
$this->post('password/reset', 'Auth\ResetPasswordController#reset');
}
So here you can change the route for /register. Don't forget to remove the Auth::routes() helper from the web.php when you do this.
Go to your Auth controller you can override the redirection
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
* Where to redirect users after login / registration.
*
* #var string
*/
protected $redirectTo = '/';

unauthorizedRedirect set to false, still redirecting

I'm writing some REST api for my cake 3.0 application, and I need to set $this->Auth->unauthorizedRedirect to false, as the manual says that this would prevent my application to redirect to login url for unauthorized requests.
http://api.cakephp.org/3.0/class-Cake.Auth.BasicAuthenticate.html
The problem is that I'm trying to set it in my Users controller, and it doesn't work:
class UsersController extends AppController {
public function initialize() {
parent::initialize();
$this->loadComponent('RequestHandler');
}
public function beforeFilter(Event $event) {
parent::beforeFilter($event);
$this->Auth->allow(['logout']);
// Change the authentication mode when using REST api
if(! $this->RequestHandler->accepts('html')) {
$this->Auth->unauthorizedRedirect = false;
$user = $this->Auth->identify();
if ($user) {
$this->Auth->setUser($user);
}
}
}
This scripts works fine as detecting if a user is actually registered, but fails when I try to use wrong authentication data, showing the login form instead of throwing an error. What am I doing wrong?
Authentication and authorization are two different things
You are mixing up authentication and authorization, that's two different things. Logging in a user is authentication, testing whether a logged in user is allowed to access a specific action is authorization.
So the unauthorized redirect configuration applies to logged in users when accessing actions.
Handling unauthenticated requests
What you are looking for, ie throw an exception on unauthenticated requests, is done by the basic authentication adapter by default, so I assume that you actually aren't using this adapter!?
So if you are using a different adapter, this behavior is best implemented in either your controller where you are trying to identify the user
$user = $this->Auth->identify();
if (!$user) {
throw new ForbiddenException('Stop! Hammer time!');
} else {
$this->Auth->setUser($user);
}
or, in case you want the exception to be thrown for every controller, in a custom authentication adapters unauthorized() method, which is being invoked on unauthenticated requests before executing possible redirects. Quote from the docs:
Cookbook > Authentication > Handling Unauthenticated Requests
When an unauthenticated user tries to access a protected page first the unauthenticated() method of the last authenticator in the chain is called. The authenticate object can handle sending response or redirection by returning a response object, to indicate no further action is necessary. Due to this, the order in which you specify the authentication provider in authenticate config matters.
If authenticator returns null, AuthComponent redirects user to login action. [...]
Here's a simple example that extends the form authentication handler:
src/Auth/MyCustomAuthenticate.php
namespace App\Auth;
use Cake\Auth\FormAuthenticate;
use Cake\Network\Exception\ForbiddenException;
use Cake\Network\Request;
use Cake\Network\Response;
class MyCustomAuthenticate extends FormAuthenticate
{
public function unauthenticated(Request $request, Response $response)
{
if(!$request->accepts('text/html')) {
throw new ForbiddenException('Ah ah ah! You didn\'t say the magic word!');
}
}
}
Controller
$this->loadComponent('Auth', [
'authenticate' => [
'MyCustom'
]
]);
See also
Cookbook > Authentication > Creating Custom Authentication Objects
Cookbook > Authentication > Using Custom Authentication Objects