简体   繁体   English

Laravel redirect()->intended() 在自定义登录控制器中不起作用

[英]Laravel redirect()->intended() is not working in custom login controller

I have a custom login controller and its using return redirect()->intended(route('home')) , as per the documentation this should send the user redirect the user to the URL they were attempting to access before being intercepted by the authentication middleware.我有一个自定义登录控制器,它使用return redirect()->intended(route('home')) ,根据文档,这应该将用户重定向到他们在被拦截之前尝试访问的 URL身份验证中间件。

But for my case every time it is redirecting to home route .I am sure i have done correctly or at least i think i have done correctly.但是对于我的情况,每次重定向到home route 。我确定我做得对,或者至少我认为我做得对。 Can anyone please tell me where i am doing this wrong ??谁能告诉我我在哪里做错了??

My logincontroller is like this:我的登录logincontroller是这样的:

public function __construct()
    {
        $this->middleware('guest');
    }

 public function login(Request $request)
    {
        $validatedData = $request->validate([
            'email' => 'required|email|max:255',
            'password' => 'required|max:255',
        ]);
        try {
            $response = HelperFunctions::fetchData('post', 'login/login', [
                'loginId' => $request->get('email'),
                'password' => md5($request->get('password'))
            ]);
            if ($response['code'] == 200 && $response['success']) {
                session([
                    'api_token' => $response['sessionId'],
                    'user_data' => $response['data']['profile']
                ]);

                return redirect()->intended(route('home'));
            } else {
                return redirect()->back()->with('error', 'Please provide valid credentials');
            }
        } catch (\Exception $e) {
            return redirect()->back()->with('error', 'Opps!! Something is wrong. We are trying to fix it');
        }

My authentication checking middleware我的认证检查中间件

class checkAuthentication
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        //check if user is logged in
        if(Session::has('api_token') && Session::has('user_data')) {
            return $next($request);
        }

        return redirect(route('login'));

    }
}

I also tried to dd() Session::get('url.intended') but it returns empty .我也尝试dd() Session::get('url.intended')但它返回 empty 。

I did tried looking for reference on google, laracast & stackoverflow i found some reference , but those did not help me.我确实尝试在 google、laracast 和 stackoverflow 上寻找参考资料,但我找到了一些参考资料,但这些对我没有帮助。 Can anyone please help me thank you.任何人都可以请帮助我谢谢。

Some of the reference i have checked & tried:我检查过并尝试过的一些参考资料:

  1. https://laracasts.com/discuss/channels/laravel/redirect-intended-not-working-after-login?page=1 https://laracasts.com/discuss/channels/laravel/redirect-intended-not-working-after-login?page=1
  2. Laravel 5 - redirect()->intended() after authentication not going to intended Laravel 5 - 身份验证后重定向()-> 预期()不打算
  3. https://laravel.io/forum/11-24-2014-problems-with-redirectintended-and-auth https://laravel.io/forum/11-24-2014-problems-with-redirectintended-and-auth

The simplest way would be to redirect()->guest() in your Auth middleware instead of the redirect you currently have:最简单的方法是在您的Auth中间件中使用redirect()->guest()而不是您当前拥有的重定向:

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

Using the guest() method on the redirector is what adds the url.intended value to the session.使用重定向器上的guest()方法将url.intended值添加到会话中。


Alternatively, instead of returning from the middleware if they're not authenticated you could throw an AuthenticationException :或者,如果中间件未通过身份验证,您可以抛出AuthenticationException ,而不是从中间件返回:

public function handle($request, Closure $next)
{
    //check if user is logged in
    if(Session::has('api_token') && Session::has('user_data')) {
        return $next($request);
    }

    throw new AuthenticationException('Unauthenticated.');
}

This will allow you to take advantage of Laravel's ExceptionHandler if you need to.如果需要,这将允许您利用 Laravel 的ExceptionHandler You will also need to add use Illuminate\\Auth\\AuthenticationException;您还需要添加use Illuminate\\Auth\\AuthenticationException; to the top of your class.到你班级的顶端。

I also tried to dd() Session::get('url.intended') but it returns empty .我也尝试 dd() Session::get('url.intended') 但它返回 empty 。

In my case, this key existed in my session, but for some weird reason, something funny happens after redirect()->intended() returns the redirect response.在我的例子中,这个键存在于我的会话中,但出于某种奇怪的原因,在redirect()->intended()返回重定向响应后发生了一些有趣的事情。 Maybe the response is discarded in transit, or intercepted by some other caller on the stack.可能响应在传输过程中被丢弃,或者被堆栈上的其他调用者拦截。

What I did to work around it was to manually obtain the intended url from the session and hand it over to the redirect (instead of relying on the underlying protocols of intended() ).我为解决这个问题所做的工作是从会话中手动获取预期的 url 并将其交给重定向(而不是依赖intended()的底层协议)。

By adding this通过添加这个

redirect(Session::get('url.intended', $this->redirectPath()));

at the bottom of LoginController@showLoginResponse , once user is authenticated, Laravel is able to remember intended url and redirect to itLoginController@showLoginResponse的底部,一旦用户通过身份验证,Laravel 就能够记住预期的 url 并重定向到它

I have also faced this problem and the best way I come up with is using the authenticated method.我也遇到过这个问题,我想出的最好方法是使用经过身份验证的方法。

So Override the authenticated method in your controller and use the intended route there.因此,覆盖控制器中的经过身份验证的方法并在那里使用预期的路由。

 /**
 * The user has been authenticated.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  mixed  $user
 * @return mixed
 */
protected function authenticated(Request $request, $user)
{
    if ($user->role == 'admin') {
        return redirect()->intended('/admin');
    } elseif ($user->role == 'user') {
        return redirect()->intended('/');
    }
}

also sometimes changing the RedirectIfAuthenticated middleware also helps.有时更改 RedirectIfAuthenticated 中间件也有帮助。 so go to App\\Http\\Middleware\\RedirectIfAuthenticated.php and edit it as well.所以去 App\\Http\\Middleware\\RedirectIfAuthenticated.php 并编辑它。

    <?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;

class RedirectIfAuthenticated
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string|null  $guard
     * @return mixed
     */
    public function handle($request, Closure $next, $guard = null)
    {
        if (Auth::guard($guard)->check()) {

            if ($request->user()->role == 'admin') {
                return redirect()->intended('/admin');
            } elseif ($request->user()->role == 'user') {
                return redirect()->intended('/');
            }
            // return redirect('/home');
        }

        return $next($request);
    }
}

Do this:做这个:

return redirect()->intended('home'); return redirect()->intended('home');

Instead of this:取而代之的是:

return redirect()->intended(route('home')); return redirect()->intended(route('home'));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM