Skip to main content

API Authentication

Premium
4 min read

An API without authentication is like a house without a door. So, let's secure our API by adding an authentication system to it:

  • Set up Sanctum Middleware
  • Create a User Registration API
  • Create a User Login API

Let's get secure!


Setting Up Authentication Middleware

Let's start by securing our API endpoint with a Middleware:

routes/api.php

// ...
 
Route::group(['middleware' => 'auth:sanctum'], function () {
Route::apiResource('categories', CategoryController::class);
Route::apiResource('transactions', TransactionController::class);
});

Now, we can immediately try to make an API request using Postman:

This is good! However, we need to create a user registration and login API to authenticate our users.


Registering our First User

So, let's create a way to register a new user. For this, we need a new Controller:

php artisan make:controller Api/AuthController

In there, let's add a new method to register a user:

app/Http/Controllers/Api/AuthController.php

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rules\Password;
 
// ...
 
public function register(Request $request): string
{
$request->validate([
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => ['required', 'confirmed', Password::defaults()],
'device_name' => 'required',
]);
 
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password),
]);
 
return $user->createToken($request->device_name)->plainTextToken;
}

As you can see, we are doing basic validation and user creation...

The Full Lesson is Only for Premium Members

Want to access all of our courses? (30 h 41 min)

You also get:

55 courses
Premium tutorials
Access to repositories
Private Discord
Get Premium for $129/year or $29/month

Already a member? Login here

Comments & Discussion

PV
Paul van Vulpen ✓ Link copied!

I would add the sanctum middleware on the logout route. Like this: Route::post('/auth/logout', [AuthController::class, 'logout'])->middleware('auth:sanctum'); . It's more secure.

T�
Trần Đức Thiều ✓ Link copied!

When I setup the authentication middleware I tried to make an API request using Postman but I don't get the same response as yours and I can't get the token. How to get 'name', 'email', 'password', 'password_confirmation' 'device_name' to appear like yours

M
Modestas ✓ Link copied!

Everything that I have set up - is in the screenshot. In this case, I'm sending these parameters as raw in postman

T�
Trần Đức Thiều ✓ Link copied!

Oh I got it. I tried again and it worked. Thank you very much.

MM
mir-mel miranda ✓ Link copied!

I was able to do every steps of this chapter successfully in my local computer, and test everything using postman. I need your help because when i tried to deploy it on my hosted server i got "message": "Unauthenticated." error message on my api/auth/logout and api/categories. I am able to received the generated token after the login using postman. Did I missed something or do I need additional configuration on my server? Thanks in advance!

M
Modestas ✓ Link copied!

You need to send that token with each of your requests as a Authentication: Bearer ${token} header. Without this - your user is not logged in

MM
mir-mel miranda ✓ Link copied!

Thanks for the reply, I already included it in the Authorization: Bearer Token, I have no problem running it my local machine but in my server I am still receiving this "message": "Unauthenticated." error.

M
Modestas ✓ Link copied!

Try to replicate this behaviour using Postman. It's hard to say what exactly can be an issue there (maybe this can be it, but not sure https://laravel.com/docs/12.x/sanctum#spa-authentication )

SI
Solomon Iroegbu ✓ Link copied!

I'm getting This after folloing your steps. Whats the reason please? The GET method is not supported for route api/auth/login. Supported methods: POST.

M
Modestas ✓ Link copied!

Not sure where you got the GET for Login (if it's in tutorial - tell me where)

But you do need to send a POST request there

SI
Solomon Iroegbu ✓ Link copied!
M
Modestas ✓ Link copied!

Not quite what I asked. But yes, this is a POST route and not GET so you should call the POST request on it

SI
Solomon Iroegbu ✓ Link copied!

I called the post request but was still getting the error.

M
Modestas ✓ Link copied!

How did you call it?

SI
Solomon Iroegbu ✓ Link copied!

Route::post('/auth/login', [AuthController::class, 'login']);

M
Modestas ✓ Link copied!

This is the definition of the route.

I'm specifically referring to:

What were you doing when you got the error back? And how were you doing it?

SI
Solomon Iroegbu ✓ Link copied!

trying to view api/auth/login

SI
Solomon Iroegbu ✓ Link copied!

Do i need to be logged in?

M
Modestas ✓ Link copied!

API routes have no views on them, so there's nothing to view. They will not work in your browser

SI
Solomon Iroegbu ✓ Link copied!

I know. I'm using Postman. Should I be expecting 200 ok

M
Modestas ✓ Link copied!

If you are sending a POST request, you need to send a email and password inside of it. From there, you will get a token response back

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.