JWT User Authentication with Lumen API

Photo by Luis Tosta on Unsplash

Install the JWT Library

composer require tymon/jwt-auth
php artisan jwt:secret

Prep Lumen

$app->withFacades();$app->withEloquent();$app->register(App\Providers\AuthServiceProvider::class);$app->routeMiddleware([
'auth' => App\Http\Middleware\Authenticate::class,
]);
$app->register(Tymon\JWTAuth\Providers\LumenServiceProvider::class);

Set up the Auth Config

<?phpreturn [
'defaults' => [
'guard' => 'api',
'passwords' => 'users',
],
'guards' => [
'api' => [
'driver' => 'jwt',
'provider' => 'users',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => \App\Models\User::class
]
]
];
php artisan make:migration create_users_tablephp artisan make:migration create_password_resets_table
Schema::create('users', function (Blueprint $table) {  $table->increments('id');  $table->string('name');  $table->string('email')->unique();  $table->timestamp('email_verified_at')->nullable();  $table->string('password');  $table->rememberToken();  $table->timestamps();});
Schema::create('password_resets', function (Blueprint $table) {  $table->string('email')->index();  $table->string('token');  $table->timestamp('created_at')->nullable();});
php artisan migrate

Set up the User Model

use Tymon\JWTAuth\Contracts\JWTSubject;
class User extends Model implements AuthenticatableContract, AuthorizableContract, JWTSubject
/**
* Retrieve the identifier for the JWT key.
*
* @return mixed
*/
public function getJWTIdentifier()
{
return $this->getKey();
}
/**
* Return a key value array, containing any custom claims to be added to the JWT.
*
* @return array
*/
public function getJWTCustomClaims()
{
return [];
}

Create Authentication Controller

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
class AuthController extends Controller
{
public function __construct() {
$this->middleware(‘auth’, [‘except’ => [‘login’, ‘register’, ]]);
}
/**
* Attempt to register a new user to the API.
*
* @param Request $request
* @return Response
*/
public function register(Request $request)
{
// Are the proper fields present?
$this->validate($request, [
‘name’ => ‘required|string|between:2,100’,
‘email’ => ‘required|string|email|max:100|unique:users’,
‘password’ => ‘required|string|min:6’,
]);
try {
$user = new User;
$user->name = $request->input(‘name’);
$user->email = $request->input(‘email’);
$plainPassword = $request->input(‘password’);
$user->password = app(‘hash’)->make($plainPassword);
$user->save();
return response()->json([‘user’ => $user, ‘message’ => ‘CREATED’], 201);
} catch (\Exception $e) {
return response()->json([‘message’ => ‘User Registration Failed!’], 409);
}
}
/**
* Attempt to authenticate the user and retrieve a JWT.
* Note: The API is stateless. This method _only_ returns a JWT. There is not an
* indicator that a user is logged in otherwise (no sessions).
*
* @param Request $request
* @return Response
*/
public function login(Request $request)
{
// Are the proper fields present?
$this->validate($request, [
‘email’ => ‘required|string’,
‘password’ => ‘required|string’,
]);
$credentials = $request->only([‘email’, ‘password’]); if (! $token = Auth::attempt($credentials)) {
// Login has failed
return response()->json([‘message’ => ‘Unauthorized’], 401);
}
return $this->respondWithToken($token);
}
/**
* Log the user out (Invalidate the token). Requires a login to use as the
* JWT in the Authorization header is what is invalidated
*
* @return \Illuminate\Http\JsonResponse
*/
public function logout() {
auth()->logout();
return response()->json([‘message’ => ‘User successfully signed out’]);
}
/**
* Refresh the current token.
*
* @return \Illuminate\Http\JsonResponse
*/
public function refresh() {
return $this->respondWithToken( auth()->refresh() );
}
/**
* Helper function to format the response with the token.
*
* @return \Illuminate\Http\JsonResponse
*/
private function respondWithToken($token)
{
return response()->json([
‘token’ => $token,
‘token_type’ => ‘bearer’,
‘expires_in’ => Auth::factory()->getTTL() * 60
], 200);}
}

Set up the Routes

/*
*
* UNAUTHENTICATED ROUTES
*
*/
$router->post( ‘/login’, ‘AuthController@login’);
$router->post( ‘/register’, ‘AuthController@register’ );
/*
*
* AUTHENTICATED ROUTES
*
*/
$router->group(
[
‘middleware’ => ‘auth’,
], function( $router ) {
$router->post( ‘/logout’, ‘AuthController@logout’ );
$router->get( ‘/refresh’, ‘AuthController@refresh’ );
$router->post( ‘/refresh’, ‘AuthController@refresh’ );
});

Congrats

Director of Engineering at Mindsize. 20+ year technology veteran. Providing leadership insights, mentorship, and coaching to new and existing leaders.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store