Build authentication into your Laravel API with JSON Web Tokens (JWT)

BarryvdhCorsHandleCors::class,];Tests for JWT AuthenticationWoohoo so it should all be working, but let’s write some tests to prove it.<?phpnamespace TestsFeature;use AppUser;use IlluminateFoundationTestingDatabaseMigrations;use TestsTestCase;class AuthenticationTest extends TestCase{ use DatabaseMigrations; public function setUp() { parent::setUp(); $user = new User([ 'email' => 'test@email.com', 'password' => '123456' ]); $user->save(); } /** @test */ public function it_will_register_a_user() { $response = $this->post('api/register', [ 'email' => 'test2@email.com', 'password' => '123456' ]); $response->assertJsonStructure([ 'access_token', 'token_type', 'expires_in' ]); } /** @test */ public function it_will_log_a_user_in() { $response = $this->post('api/login', [ 'email' => 'test@email.com', 'password' => '123456' ]); $response->assertJsonStructure([ 'access_token', 'token_type', 'expires_in' ]); } /** @test */ public function it_will_not_log_an_invalid_user_in() { $response = $this->post('api/login', [ 'email' => 'test@email.com', 'password' => 'notlegitpassword' ]); $response->assertJsonStructure([ 'error', ]); }}Theses tests go through and test that we get the right response formats..Pushing up the source code to GitHub!Source code on GitHubExtra resourcesThese were helpful resources apart from the official documentation that were helpful in making sense of JWT authentication in Laravel.Build a REST API with Laravel API resources by Chimezie Enyinnayalaravel-api-boilerplate-jwt by Francesco Malatesta. More details

Leave a Reply