Back to Course |
How to Build Laravel 11 API From Scratch

Authentication with Laravel Sanctum and Mobile Apps

Let's briefly talk about a third way of authentication with Sanctum, this time for mobile applications.

Unfortunately, I am not a mobile app developer, so I won't be able to do a demo project. But this course is about building a backend, so we will see how to authenticate a user.


Issuing a token is very similar to how it is done when issuing a token for API-based authentication. A sanctum/token POST route should replace the login mechanism.

Here is an example of the callback function, but you should use a Controller.

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;
 
Route::post('/sanctum/token', function (Request $request) {
$request->validate([
'email' => 'required|email',
'password' => 'required',
'device_name' => 'required',
]);
 
$user = User::where('email', $request->email)->first();
 
if (! $user || ! Hash::check($request->password, $user->password)) {
throw ValidationException::withMessages([
'email' => ['The provided credentials are incorrect.'],
]);
}
 
return $user->createToken($request->device_name)->plainTextToken;
});

When authenticating, you pass the user's device name beside the user's email and password. However, identifying the device name is up to you. The only thing it should be a unique name.

Then, usually check if the email exists and the password is correct. Finally, we create a token by passing the device name as a token name.

And then it's the same as with regular API. When sending an API request the token needs to passed in the Authorization header as a Bearer token. The token itself should be saved on the mobile device.

Protecting routes is the same as using the auth:sanctum Middleware.