A tutorial to demonstrate how to add authorization to a Laravel API with Magic's Laravel Plugin.
$ git clone https://github.com/magiclabs/example-laravel-api.git
$ cd example-laravel-api
$ mv .env.example .env
$ composer install
Sign Up with Magic and get your MAGIC_SECRET_KEY
.
MAGIC_SECRET_API_KEY=sk_live_123...
To get the DID Token for testing, fork our Laravel API Authorization template in CodeSandBox.
Replace the pk_test_123...
string with your Publishable API Key
from the Magic Dashboard: on line 46
/* 2️⃣ Initialize Magic Instance */
const magic = new Magic("Publishable API Key");
You now have a working Frontend Application.
Login and copy the DID Token
for Testing the API with Postman.
The routes shown below are available for the following requests:
GET /api/public
: available for non-authenticated requestsGET /api/private
: available for authenticated requests containing a DID Token
The /api/private
route is now only accessible if a valid DID Token is included in the Authorization
header of the incoming request.
Now, let’s start the Laravel server locally:
php artisan serve --port=8001
Send a GET
request to the public route - http://localhost:8001/api/public
- and you should receive back:
{
"message": "Hello from a public endpoint! You don't need to be authenticated to see this."
}
Now send a GET
request to the private route - http://localhost:8001/api/private
- and you should get a 401 status and the following message:
{ "message": "Bearer token missing" }
Add an Authorization
header set to Bearer DID_TOKEN
using the token generated above. Send the GET
request to the private route again and you should see:
{
"message": "Hello from a private endpoint! You need to have a valid DID Token to see this.",
"user": {
"email": "your_email@provide.com",
"issuer": "did:ethr:0xaa12b334C1f3d……….62367e5B8e",
"public_address": "0xaa12b334C1f3d……….62367e5B8e"
}
}
The Laravel API Authorization with Magic Example is open-sourced software licensed under the MIT license.