API Authentication in Laravel with Sanctum

Laravel ~ 8 minutes

# Why we need API authentication

Hello again! In this tutorial, we will protect a Laravel API with Laravel Sanctum. Sanctum is a small and light package. It gives each user a secret token. The user sends this token with every request, and Laravel knows who is calling.

Why do we need this? Think about a mobile app. The app talks to your server through an API. The server must be sure that the person is really who they say they are. A token solves this problem in a simple way.

What we will build

  • A register and login endpoint that gives a token
  • A protected route that needs the token
  • A logout endpoint that deletes the token
  • A quick test using curl

You can always read more in the Sanctum documentation. Let us begin, step by step.

Install API support
Code Copied to Clipboard

# What the install command does

This command is the easy way to start in new Laravel versions. It installs Sanctum for you. It also creates the file routes/api.php, and it adds a migration for the personal_access_tokens table.

This table stores every token that you give to your users. Each row has the token name, a hashed token value, and the user it belongs to. Please note that Laravel stores only a hash of the token. So even if someone sees your database, they cannot use the real tokens.

If you use an older Laravel version, you may need to run composer require laravel/sanctum first. The Sanctum docs explain this clearly.

Next, we must tell the User model that it can have tokens.

Add the HasApiTokens trait
Code Copied to Clipboard

# Understanding the trait

A trait in PHP is a group of ready methods that you can add to a class. The HasApiTokens trait gives your user a few new methods.

Methods the trait gives you

  • createToken('name') makes a new token
  • tokens() returns all tokens of the user
  • currentAccessToken() returns the token used in this request

Without this trait, you would see an error like Call to undefined method createToken. So please do not forget it. After you add it, we need to build the new table in the database.

Run the migrations
Code Copied to Clipboard

# Write the login logic

Very good. Now the database is ready. Let us write the login code. We will make a small controller method. It checks the email and password. If they are right, it returns a new token. If they are wrong, it returns an error message.

We use the Hash::check method to compare the plain password with the stored hash. Never compare passwords with ==, because passwords are always stored as hashes.

We also return the status code 401. This code means Unauthorized. Good APIs always use the correct status code, so the client app can react in the right way.

AuthController login method
Code Copied to Clipboard

The code continues

The method above is not finished yet. The last part creates the token and sends it back. We will write it in the next code block, so each piece stays small and easy to read.

Also, one tip about security. We return the same message, Invalid login, for a wrong email and a wrong password. This is on purpose. If we said email not found, an attacker could learn which emails exist in our system. A calm and equal message is safer.

# Create and return the token

Now, please look at the last lines of the method. We call createToken on the user and give the token a name, such as mobile-app. The name helps you know where the token came from.

The result has a property called plainTextToken. This is the real token string. You can see it only once. After this moment, Laravel keeps only the hash. So we must send it to the client now, and the client must save it.

We then close the method with a normal brace.

Finish the login method
Code Copied to Clipboard

# Protect the routes

Next, we need to connect the controller to routes. Open routes/api.php. Public routes, like login, stay outside any group. Private routes go inside a group that uses the auth:sanctum middleware.

A middleware is a small guard that checks each request before it reaches your controller. The auth:sanctum guard looks for the header Authorization: Bearer your-token. If the token is missing or wrong, Laravel returns a 401 answer by itself. You do not need to write that check yourself.

Let us see the route file.

routes/api.php
Code Copied to Clipboard

# Start the server

Now it is time to test our work. First, we need a running server. Laravel has a small built in server that is perfect for learning. Please open a terminal inside your project folder and run the command below.

Keep this terminal open. The server will keep running there. Then open a second terminal window for the next commands. By default, the server listens on http://127.0.0.1:8000.

Also, please make sure you have at least one user in your database. You can create one with a seeder or with Tinker.

Run the development server
Code Copied to Clipboard

# Test the login

In the second terminal, we will use curl to call our API. Curl is a tool that sends web requests from the command line. It is available on most computers.

We add the header Accept: application/json. This is very important for APIs. It tells Laravel that we want JSON back, and not a web page. Without it, errors may redirect you to a login page, and that will confuse you.

Please change the email and password to match your own user.

Call the login endpoint
Code Copied to Clipboard

# Use the token

If everything is right, you will see JSON with a token field. It looks like 1|abcdef.... Copy the whole value. Now we will call the protected route /api/me and send the token in the Authorization header.

The word Bearer comes before the token. It means the one who bears this token is allowed in. Replace YOUR_TOKEN in the command with your real token.

If you send the request without the header, you will get a 401 error. That proves the route is truly protected.

Call a protected route
Code Copied to Clipboard

# Logout and revoke tokens

A good API also lets the user log out. With Sanctum, logout means deleting the token. When the token row is gone, the token cannot be used again, even if someone copied it.

We can delete only the current token, so the user stays logged in on other devices. Or we can delete all tokens, so the user is logged out everywhere. Both are one line of code.

Here is the logout method.

AuthController logout method
Code Copied to Clipboard
Keep your tokens safe

Please remember these important safety rules. A token works like a password. Anyone who has it can act as the user.

Safety checklist

  • Always use HTTPS on a real server, never plain HTTP
  • Never show tokens in logs or error messages
  • Give tokens an expiry time in the config/sanctum.php file
  • Use token abilities to limit what a token can do
  • Delete old tokens when a user changes their password

Also note that Sanctum has two modes. Token mode is for mobile apps and other clients. Cookie mode is for your own single page app on the same main domain. This tutorial used token mode. You can read about both in the official guide.

# Summary and next steps

Excellent work! You have built a complete token login system. Let us remember the main steps.

Summary

  • Install API support with php artisan install:api
  • Add the HasApiTokens trait to the User model
  • Check the password and return createToken(...)->plainTextToken
  • Protect routes with the auth:sanctum middleware
  • Send the token as a Bearer header, and delete it on logout

What to learn next

  • Token abilities and scopes
  • Rate limiting for login routes
  • Writing automated tests for your API

In the next tutorial, you may also like to read about good REST API design. Thank you for learning with us, and see you soon!