LoginSignup
1
2

More than 1 year has passed since last update.

LaravelのAuth::attempt()がfalseを返し続ける

Last updated at Posted at 2022-01-22

TL;DR

パスワードはハッシュしてストアしましょう

経緯

久々にLaravelの認証を触ったら小一時間ほどハマった……

問題部分のコード

本当は例外処理を色々書いてるけど、削ってシンプルにしてます。

  • registerメソッド:「名前」「メールアドレス」「パスワード」を入れるとUserを一つcreateする。
  • loginメソッド:「メールアドレス」「パスワード」を入れると、Auth::attemptで該当するUserを拾ってくる。次にトークンを生成し、cookieにくっつけてUserと一緒に返す。

という、とても典型的な認証処理です。

App\Http\Controllers\AuthController.php
class AuthController extends Controller
{
    public function register(Request $req){
            $user = User::create(
                $req->only("name","email","password")
            );
            $jwt = $user->createToken("token")->plainTextToken;
            $cookie = cookie("jwt",$jwt, 60 * 24);
            return response(["user"=>$user]);
    }
    public function login(Request $req){
        if(!Auth::attempt($req->only("email","password"))){
            return response([
                "error" => "invalid credentials"
            ],Response::HTTP_UNAUTHORIZED);
        }
        $user = Auth::user();
        $jwt = $user->createToken("token")->plainTextToken;
        $cookie = cookie(
            "jwt",$jwt, 60 * 24
        );
        return response([
            "user"=>$user
        ])->withCookie($cookie);
    }

発生した問題

AughController::login()がうまく動かない……。
php artisan tinkerで調べてみたところ、どうもAuth::attemptの挙動がおかしい様子。正しいemailとpasswordを入れているのにfalseを返す。

原因と解決

Auth::attemptはパスワードがハッシュされている前提でusersテーブルを検索します。したがってregisterメソッド内でUser::create()する際、パスワードはハッシュしてストアしなければならないとのこと。ド基本だよ!!!
というわけで、registerメソッドを以下のように変更します。

    public function register(Request $req){
            $user = User::create([
                "name"=>$req->input("name"),
                "email"=>$req->input("email"),
                "password"=>Hash::make($req->input("password")),
            ]);
            $jwt = $user->createToken("token")->plainTextToken;
            $cookie = cookie("jwt",$jwt, 60 * 24);
            return response(["user"=>$user]);
    }

久々に触ると基本的なことも分かんなくなっているもんですな……。
バカ!バカ!あたいのバカ!
というわけで備忘録として残しておきます。

参考 Auth::attempt($credentials) Always returns false in Laravel 8.76.2 -Stack Overflow

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2