質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Laravel

LaravelとはTaylor Otwellによって開発された、オープンソースなPHPフレームワークです。Laravelはシンプルで表現的なシンタックスを持ち合わせており、ウェブアプリケーション開発の手助けをしてくれます。

PostgreSQL

PostgreSQLはオープンソースのオブジェクトリレーショナルデータベース管理システムです。 Oracle Databaseで使われるPL/SQLを参考に実装されたビルトイン言語で、Windows、 Mac、Linux、UNIX、MSなどいくつものプラットフォームに対応しています。

PHP

PHPは、Webサイト構築に特化して開発されたプログラミング言語です。大きな特徴のひとつは、HTMLに直接プログラムを埋め込むことができるという点です。PHPを用いることで、HTMLを動的コンテンツとして出力できます。HTMLがそのままブラウザに表示されるのに対し、PHPプログラムはサーバ側で実行された結果がブラウザに表示されるため、PHPスクリプトは「サーバサイドスクリプト」と呼ばれています。

Q&A

解決済

1回答

2268閲覧

【Laravel】Authのログイン認証用のテストコードで認証されない

okamotosan

総合スコア5

Laravel

LaravelとはTaylor Otwellによって開発された、オープンソースなPHPフレームワークです。Laravelはシンプルで表現的なシンタックスを持ち合わせており、ウェブアプリケーション開発の手助けをしてくれます。

PostgreSQL

PostgreSQLはオープンソースのオブジェクトリレーショナルデータベース管理システムです。 Oracle Databaseで使われるPL/SQLを参考に実装されたビルトイン言語で、Windows、 Mac、Linux、UNIX、MSなどいくつものプラットフォームに対応しています。

PHP

PHPは、Webサイト構築に特化して開発されたプログラミング言語です。大きな特徴のひとつは、HTMLに直接プログラムを埋め込むことができるという点です。PHPを用いることで、HTMLを動的コンテンツとして出力できます。HTMLがそのままブラウザに表示されるのに対し、PHPプログラムはサーバ側で実行された結果がブラウザに表示されるため、PHPスクリプトは「サーバサイドスクリプト」と呼ばれています。

0グッド

0クリップ

投稿2020/07/16 07:36

編集2020/07/16 07:37

Authによるログイン機能を実装しました。

ログイン部分に関するテストコードを書きたいのですが、
テストコード側での認証がうまくいきません(実際の画面では問題なし)
何か記述間違いや漏れがあるかどうか教えていただけませんか?

動作環境
PHP 7.1
Laravel 7.5.1
postgres 9.5

ログインに関する設計

・コードとパスワードを画面にて入力し認証する
DB側のカラム名は、コードはcode,パスワードはpswdとなっています。
・パスワード認証の方式はmd5を採用

app/Users.php

<?php namespace App; use Illuminate\Contracts\Auth\MustVerifyEmail; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; class User extends Authenticatable { use Notifiable; /** * Get the password for the user. * * @return string */ public function getAuthPassword() { return $this->pswd; } /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'name', 'email', 'password', ]; /** * The table associated with the model. * * @var string */ protected $table = 'xxxxxx'; /** * The primary key for the model. * * @var string */ //protected $primaryKey = 'code'; }

app/Http/Controllers/LoginController.php

<?php //namespace App\Http\Controllers\Auth; namespace App\Http\Controllers\Auth; use App\Http\Controllers\Controller; use App\Providers\RouteServiceProvider; use Illuminate\Foundation\Auth\AuthenticatesUsers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use App\Users; class LoginController extends Controller { /* |-------------------------------------------------------------------------- | Login Controller |-------------------------------------------------------------------------- | | This controller handles authenticating users for the application and | redirecting them to your home screen. The controller uses a trait | to conveniently provide its functionality to your applications. | */ use AuthenticatesUsers; /** * Where to redirect users after login. * * @var string */ protected $redirectTo = '****'; /** * Create a new controller instance. * * @return void */ public function __construct() { $this->middleware('guest')->except('logout'); } protected function loggedOut(\Illuminate\Http\Request $request) { return redirect('/login'); } //codeをusernameに設定 public function username() { return 'code'; } protected function attemptLogin(Request $request) { $user = User::where([ 'code' => $request->code, 'pswd' => md5($request->password) ])->first(); //dump($request->password); if ($user) { $this->guard()->login($user, $request->has('remember')); return true; } return false; } }

実際のテスト用ファイル
AuthenticationTest.php

<?php namespace Tests\Feature; use App\User; use Illuminate\Support\Facades\Auth; use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Foundation\Testing\WithFaker; use Tests\TestCase; class AuthenticationTest extends TestCase { /** * A basic feature test example. * * @return void */ use RefreshDatabase; protected $user; public function setUp(): void { parent::setUp(); // テストユーザ作成 $this->user = factory(User::class)->create(); //dd($this->user); } public function testAccsesLogin(): void{ $response = $this->get('/login'); $response->assertStatus(200); } /* public function testAccsesKintai(): void{ $response = $this->get('/kintai'); $response->assertStatus(200); }*/ public function testLogin(): void { // dd($this->user->code); //dd($this->user->pswd); $response = $this->json('POST', route('login'), [ 'code' => $this->user->code, 'password' => $this->user->pswd, ]); //dd($response); $this->assertAuthenticatedAs($this->user); //$this->assertAuthenticatedAs($user); } }

UserFactory.php

<?php /** @var \Illuminate\Database\Eloquent\Factory $factory */ use App\Users; use Faker\Generator as Faker; use Illuminate\Support\Str; /* |-------------------------------------------------------------------------- | Model Factories |-------------------------------------------------------------------------- | | This directory should contain each of the model factory definitions for | your application. Factories provide a convenient way to generate new | model instances for testing / seeding your application's database. | */ $factory->define(User::class, function (Faker $faker) { return [ 'code' => $faker->randomElement($array = ['a001','b002','c003']), 'name' => $faker->name, 'pswd' => md5('12345'), ]; });

error

The current user is not authenticated. Failed asserting that null is not null. at tests/Feature/AuthenticationTest.php:61 57| 'code' => $this->user->code, 58| 'password' => $this->user->pswd, 59| ]); 60| //dd($response); > 61| $this->assertAuthenticatedAs($this->user); 62| //$this->assertAuthenticatedAs($user);

dd($response)のメッセージの一部

+original: array:2 [ "message" => "The given data was invalid." "errors" => array:1 [ "code" => array:1 [ 0 => "ログインできません。入力した情報に誤りがないかご確認ください。" ] ] ]

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

ベストアンサー

詳しくないので検討違いだったらすみません。

// AuthenticationTest@testLogin $response = $this->json('POST', route('login'), [ 'code' => $this->user->code, 'password' => $this->user->pswd, ]);

とありますが、'password'に設定されているのは、md5にてハッシュ化された値なのではないでしょうか?
認証時、postされてきた「ハッシュ化されたパスワード」をさらにハッシュ化して判定している為、通らないのではないでしょうか?

投稿2020/07/17 00:01

meshi_s

総合スコア276

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

okamotosan

2020/07/17 02:30

ご指摘の通りでした!ありがとうございます。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問