【问题标题】:Laravel 7 custom authentication does not workLaravel 7 自定义身份验证不起作用
【发布时间】:2020-09-02 03:22:47
【问题描述】:

我正在尝试在 Laravel 7 应用程序中进行自定义身份验证。参考官方文档我应该在LoginController中添加一个公共函数authenticate(),所以我试了一下:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class LoginController extends Controller
{
    /**
     * Handle an authentication attempt.
     *
     * @param  \Illuminate\Http\Request $request
     *
     * @return Response
     */
    public function authenticate(Request $request)
    {
         eval(\Psy\sh()); //console debug line

        $credentials = $request->only('email', 'password');

        if (Auth::attempt($credentials)) {
            // Authentication passed...
            return redirect()->intended('dashboard');
        }
    }
}

但似乎该功能在登录时没有运行。我通过添加调试行eval(\Psy\sh()); 进行了测试,但它只是没有运行。 知道如何使函数运行吗?

【问题讨论】:

  • 你的执行是否命中了认证功能?执行dd("Here!") 以确保它达到该功能,请确认,
  • @kunz398 是的,我做到了。它没有达到功能。
  • 好的,所以我们可以得出结论,它甚至没有去那里你需要找到它击中的路线,然后编辑你的问题
  • 但其他功能,如 authenticated 和 showLoginForm 工作正常。这让我很困惑。

标签: php laravel-7


【解决方案1】:

错误在这里...

public function authenticate(Request $request)

Laravel 7.x 版本内置身份验证不包含在 LoginController.php 中进行身份验证的方法

所以请将其替换为经过身份验证的,如下所示。

public function authenticated(Request $request)
{
    $credentials = $request->only('email', 'password');
    if (Auth::attempt($credentials)) {
        return redirect()->intended('dashboard');
    }
}

【讨论】:

  • 我正在使用这个函数public function authenticate(Request $request)根据官方文档。请参考:laravel.com/docs/7.x/authentication#authenticating-users
  • 好的,但是尝试使用经过身份验证的名称来实现它可能会起作用。
  • 这些功能有不同的用途,不是吗?顾名思义,authenticate 是在用户认证过程中执行的,而 authenticated 是在用户认证之后执行的。
【解决方案2】:

我认为 Laravel 7 的旧版本没有 authenticated 方法,但使用 Laravel 7.30.6,您可以像这样替换 LoginController 中的 attemptLogin 方法:

public function attemptLogin(Request $request)
{
    $credentials = $request->only('email', 'password');
    return Auth::attempt($credentials, $request->filled('remember'));
}

或者如果你想指定额外的条件,你可以像这样替换attemptLogin

public function attemptLogin(Request $request)
{
    $credentials = $request->only('email', 'password');
    return Auth::attempt(['email' => $credentials['email'], 'password' => $credentials['password'], 'role_id' => 1], $request->filled('remember'));
}

后者根据文档:Manually Authenticating Users in Laravel 7.x

【讨论】:

    猜你喜欢
    • 2018-08-05
    • 1970-01-01
    • 2015-02-23
    • 2017-01-26
    • 1970-01-01
    • 2016-10-21
    • 1970-01-01
    相关资源
    最近更新 更多