DEV Community

Robertino
Robertino

Posted on

🛠 Build and Secure a Laravel API

📕 In this tutorial, you'll learn how to create a simple Laravel API and add authorization to it using Auth0. You can find the final code in this GitHub repository.


Getting Started

In this tutorial, you'll learn how to create a simple Laravel API and add authorization to it using Auth0. You can find the final code in this GitHub repository.

👋 If you already have a Laravel API that you want to secure, you can go ahead and skip to the "Secure your Laravel API" section.

Prerequisites

This tutorial uses the latest version of Laravel at the time of writing (v8). I will assume you have some basic knowledge of Laravel. If you're new to Laravel, Build a Laravel CRUD Application with Authentication may be a better primer for you!

You'll also need the following:

What you'll build

You'll be building a simple API with a single /comment resource. The API should allow anyone to view comments. However, only authorized users should be able to create, update, or delete a comment.

Public endpoints:

  • GET /comments — Return all comments
  • GET /comments/{id} — Return the comment with the specified id

Private endpoints:

  • POST /comments — Add a new comment
  • PUT /comments/{id} — Update the comment with the specified id
  • DELETE /comments/{id} — Delete the comment with the specified id

Setting Up Your Laravel Application

Installation

First, start by creating your new Laravel application. Make sure you have Composer installed, and then run the following:

composer create-project laravel/laravel laravel-api-auth
cd laravel-api-auth
php artisan serve
Enter fullscreen mode Exit fullscreen mode

You can now view your starter Laravel application at http://localhost:8000!

Laravel starter app

👩‍💻 Tip: There are several other options for starting a new Laravel project. You can now even run your Laravel project with Docker using the brand new Laravel Sail.

Sign up for Auth0

Next, you need to sign up for a free Auth0 account if you don't already have one.

Your free account allows you to easily add authentication and authorization to your applications. You'll also have access to:

You'll go through a short sign-up process where you'll create your Auth0 tenant. Once you've finished, leave the dashboard open, as you'll be revisiting it soon.

Read more...

Top comments (0)