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? (36 h 00 min)

You also get:

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

Already a member? Login here

Paul van Vulpen avatar

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.

Trần Đức Thiều avatar
Trần Đức Thiều

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

Modestas avatar

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

Trần Đức Thiều avatar
Trần Đức Thiều

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

mir-mel miranda avatar

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!

Modestas avatar

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

mir-mel miranda avatar

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.

Modestas avatar

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 )

Solomon Iroegbu avatar

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.

Modestas avatar

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

Modestas avatar

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

Solomon Iroegbu avatar

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

Modestas avatar

How did you call it?

Solomon Iroegbu avatar

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

Modestas avatar

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?

Solomon Iroegbu avatar

trying to view api/auth/login

Solomon Iroegbu avatar

Do i need to be logged in?

Modestas avatar

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

Solomon Iroegbu avatar

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

Modestas avatar

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.