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

时间:2018-08-16 18:03:01

标签: php laravel laravel-5 laravel-4

我有一个自定义的登录控制器,它使用return redirect()->intended(route('home')),根据文档,这应该向用户发送重定向用户到他们尝试访问的URL,然后被身份验证中间件拦截。

但是对于我来说,每次重定向到home route时。我确定我做得正确,或者至少我认为我做得正确。谁能告诉我我在哪里做错了吗?

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

我的身份验证检查中间件

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

    }
}

我还尝试了dd() Session::get('url.intended'),但它返回了空值。

我确实尝试过在Google,laracast和stackoverflow上寻找参考,但是我发现了一些参考,但是这些并没有帮助我。谁能帮我谢谢你。

我已经检查并尝试过一些参考文献:

  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
  3. https://laravel.io/forum/11-24-2014-problems-with-redirectintended-and-auth

4 个答案:

答案 0 :(得分:3)

最简单的方法是在ng-app中间件中redirect()->guest()

Auth

在重定向器上使用return redirect()->guest(route('login')); 方法将guest()值添加到会话中。


或者,如果未通过身份验证,则可以从中间件返回,而可以抛出url.intended

AuthenticationException

如果需要,这将允许您利用Laravel的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.'); } 。您还需要在班级顶部添加ExceptionHandler

答案 1 :(得分:0)

执行以下操作:

  

return redirect()->打算使用('home');

代替此:

  

return redirect()->打算使用(route('home'));

答案 2 :(得分:0)

  

我还尝试了dd()Session :: get('url.intended'),但它返回了空值。

在我的情况下,该密钥存在于我的会话中,但是出于某些奇怪的原因,在redirect()->intended()返回重定向响应之后,发生了一些有趣的事情。也许响应在传输过程中被丢弃,或者被堆栈中的其他调用者拦截。

要解决此问题,我要做的是从会话中手动获取所需的URL,并将其移交给重定向(而不是依靠intended()的基础协议)。

通过添加

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

位于LoginController@showLoginResponse底部,用户通过身份验证后,Laravel可以记住预期的URL并重定向到该URL。

答案 3 :(得分:0)

我也遇到了这个问题,我想出的最好方法是使用经过身份验证的方法。

因此请在您的控制器中覆盖经过身份验证的方法,并在其中使用预期的路由。

 /**
 * 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('/');
    }
}

有时也会更改RedirectIfAuthenticated中间件也有帮助。 因此请转到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);
    }
}