首页 > 解决方案 > Laravel登录 - 失败条件不起作用

问题描述

我正在 Laravel 中创建一个登录 api。

我有登录方法

public function authenticate(Request $request)
    {
        $credentials = $request->only('email', 'password');

        if (Auth::attempt($credentials)) {
            return response()->json(auth()->user());
        }

        return Response::json(['message' => 'Failed to authenticate'], 401);
    }

如果登录失败,则不会出现 401 错误。有什么理由吗?

标签: phplaravelauthenticationlaravel-5

解决方案


尝试

public function authenticate(Request $request)
{
    $credentials = $request->only('email', 'password');

    if (Auth::attempt($credentials)) {
        return response()->json(auth()->user());
    }
    else {
       return Response::json(['message' => 'Failed to authenticate'], 401);
    }
}

我也希望dd()auth()确保事情按预期进行。你在传递你的 CSRF 令牌吗?

你也有你Response使用使用../../Response加载的吗?在控制器的顶部?


推荐阅读