0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【過去ログ 2024】Laravel Sanctum

0
Posted at

SanctumAPIトークン認証SPA認証が混ざっている。
片方だけ使うつもりで間違った使い方をしていることがある。

createTokenメソッド自体がsanctumtraitHasApiTokensにあるため、これを利用するとguardsanctumとなる

にある通り、sanctumパッケージ自体がいくつもの認証のために作られており、attemptなんかはcookie認証。
createTokenAPIToken認証である

$query = Administrator::query()
        ->where('login_id', $request->login_id);
    if (!$query->exists()) {
        abort(401, 'ログインに失敗しました');
    }
    $administrator = $query->first();

if(
//認証
// attemptはcookie認証でありAPIではサポートされない
// https://stackoverflow.com/questions/68255192/laravel-sanctum-delete-current-user-token-not-working
// APIトークンを使う以上ガードはsanctumになるのでガードは意味がない
// !Auth::guard('admin')->attempt($request->only('login_id', 'password'))
!$administrator || !Hash::check($request->password, $administrator->password)
){
  //abort...
}

$token = $admin->createToken(self::TOKEN_NAME, [self::TOKEN_ABILITY])->plainTextToken;

return response()->json([
    'access_token' => $token,
    'token_type' => 'Bearer',
]);
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?