A Laravel 5.8 API Boilerplate to create a ready-to-use REST API in seconds.

Overview

Laravel API Boilerplate (JWT Edition) for Laravel 5.8

Build Status

Laravel API Boilerplate is a "starter kit" you can use to build your first API in seconds. As you can easily imagine, it is built on top of the awesome Laravel Framework. This version is built on Laravel 5.8!

It is built on top of three big guys:

What I made is really simple: an integration of these three packages and a setup of some authentication and credentials recovery methods.

Installation

  1. run composer create-project francescomalatesta/laravel-api-boilerplate-jwt myNextProject;
  2. have a coffee, nothing to do here;

Once the project creation procedure will be completed, run the php artisan migrate command to install the required tables.

Usage

I wrote a couple of articles on this project that explain how to write an entire sample application with this boilerplate. They cover the older version of this boilerplate, but all the concepts are the same. You can find them on Sitepoint:

Just be aware that some options in the config/boilerplate.php file are changed, so take a look to it.

WARNING: the articles are old and Laravel 5.1 related. Just use them as "inspiration". Even without updated tutorials, they should be enough.

Main Features

Ready-To-Use Authentication Controllers

You don't have to worry about authentication and password recovery anymore. I created four controllers you can find in the App\Api\V1\Controllers for those operations.

For each controller there's an already setup route in routes/api.php file:

  • POST api/auth/login, to do the login and get your access token;
  • POST api/auth/refresh, to refresh an existent access token by getting a new one;
  • POST api/auth/signup, to create a new user into your application;
  • POST api/auth/recovery, to recover your credentials;
  • POST api/auth/reset, to reset your password after the recovery;
  • POST api/auth/logout, to log out the user by invalidating the passed token;
  • GET api/auth/me, to get current user data;

Separate File for Routes

All the API routes can be found in the routes/api.php file. This also follow the Laravel 5.5 convention.

Secrets Generation

Every time you create a new project starting from this repository, the php artisan jwt:generate command will be executed.

Configuration

You can find all the boilerplate specific settings in the config/boilerplate.php config file.

<?php

return [

    // these options are related to the sign-up procedure
    'sign_up' => [
        
        // this option must be set to true if you want to release a token
        // when your user successfully terminates the sign-in procedure
        'release_token' => env('SIGN_UP_RELEASE_TOKEN', false),
        
        // here you can specify some validation rules for your sign-in request
        'validation_rules' => [
            'name' => 'required',
            'email' => 'required|email',
            'password' => 'required'
        ]
    ],

    // these options are related to the login procedure
    'login' => [
        
        // here you can specify some validation rules for your login request
        'validation_rules' => [
            'email' => 'required|email',
            'password' => 'required'
        ]
    ],

    // these options are related to the password recovery procedure
    'forgot_password' => [
        
        // here you can specify some validation rules for your password recovery procedure
        'validation_rules' => [
            'email' => 'required|email'
        ]
    ],

    // these options are related to the password recovery procedure
    'reset_password' => [
        
        // this option must be set to true if you want to release a token
        // when your user successfully terminates the password reset procedure
        'release_token' => env('PASSWORD_RESET_RELEASE_TOKEN', false),
        
        // here you can specify some validation rules for your password recovery procedure
        'validation_rules' => [
            'token' => 'required',
            'email' => 'required|email',
            'password' => 'required|confirmed'
        ]
    ]

];

As I already said before, this boilerplate is based on dingo/api and tymondesigns/jwt-auth packages. So, you can find many informations about configuration here and here.

However, there are some extra options that I placed in a config/boilerplate.php file:

  • sign_up.release_token: set it to true if you want your app release the token right after the sign up process;
  • reset_password.release_token: set it to true if you want your app release the token right after the password reset process;

There are also the validation rules for every action (login, sign up, recovery and reset). Feel free to customize it for your needs.

Creating Endpoints

You can create endpoints in the same way you could to with using the single dingo/api package. You can read its documentation for details. After all, that's just a boilerplate! :)

However, I added some example routes to the routes/api.php file to give you immediately an idea.

Cross Origin Resource Sharing

If you want to enable CORS for a specific route or routes group, you just have to use the cors middleware on them.

Thanks to the barryvdh/laravel-cors package, you can handle CORS easily. Just check the docs at this page for more info.

Tests

If you want to contribute to this project, feel free to do it and open a PR. However, make sure you have tests for what you implement.

In order to run tests:

  • be sure to have the PDO sqlite extension installed in your environment;
  • run php vendor/bin/phpunit;

Feedback

I currently made this project for personal purposes. I decided to share it here to help anyone with the same needs. If you have any feedback to improve it, feel free to make a suggestion, or open a PR!

Comments
  • Token Signature could not be verified and correct middleware name?

    Token Signature could not be verified and correct middleware name?

    In the documentation api.auth is used as middleware, but in the routes/api.php file jwt.auth is written, which one is the correct one to use?

    Creating a token goes perfect, but when I try to get the '/protected' route in routes/api.php I get the following errors.

    When my route middleware is

    $api->group(['middleware' => 'jwt.auth'], function(Router $api) {
    
    // token_invalid
    

    When my route middleware is api.auth

    $api->group(['middleware' => 'api.auth'], function(Router $api) {
    
    // Token Signature could not be verified.
    
    opened by notflip 11
  • Token is expired response when calling jwt.refresh route

    Token is expired response when calling jwt.refresh route

    I'm trying to refresh the token from React, using the (get) /api/refresh route but it's giving me the following error

    {"error":{"message":"Token has expired","status_code":401}}

    I am sending the current (expired) token using

    {headers: {'Authorization': Bearer ${token}}}

    Any idea what's happening here?

    opened by notflip 7
  • After migrating to server

    After migrating to server

    Hi @francescomalatesta,

    I've migrated this boilerplate to my Laravel Forge environment (via git). First I needed to manually add the following folders to mitigate the first problems:

    • ./bootstrap/cache
    • ./storage/framework/cache (excluded services.php file)

    The api routes seem to be functioning.

    The only resulting error when visiting the app root welcome url is:

    InvalidArgumentException in Compiler.php line 36:
    Please provide a valid cache path.
    

    Any clue how to fix this?

    I've used the environment included below (masked some sensitive info with <...>):

    APP_URL=<...>
    APP_KEY=base64:<...>
    APP_LOCALE=nl
    APP_ENV=production
    # APP_ENV=local
    APP_DEBUG=true
    
    DB_USERNAME=<...>
    DB_PASSWORD=<...>
    DB_DATABASE=<...>
    
    CACHE_DRIVER=file
    SESSION_DRIVER=file
    QUEUE_DRIVER=sync
    
    # MAIL_DRIVER=mailgun
    # MAILGUN_DOMAIN=<...>
    # MAILGUN_SECRET=<...>
    
    API_PREFIX=api
    API_VERSION=v1
    API_STRICT=false
    API_DEBUG=false
    
    API_SIGNUP_TOKEN_RELEASE=true
    API_RESET_TOKEN_RELEASE=true
    [email protected]
    
    opened by sandervanhooft 6
  • Wrong php version restriction

    Wrong php version restriction

    Project contains composer.lock file and after execute composer install I have following errors:

     Problem 1
        - Installation request for doctrine/annotations v1.5.0 -> satisfiable by doctrine/annotations[v1.5.0].
        - doctrine/annotations v1.5.0 requires php ^7.1 -> your PHP version (7.0.22) does not satisfy that requirement.
      Problem 2
        - Installation request for doctrine/instantiator 1.1.0 -> satisfiable by doctrine/instantiator[1.1.0].
        - doctrine/instantiator 1.1.0 requires php ^7.1 -> your PHP version (7.0.22) does not satisfy that requirement.
      Problem 3
        - doctrine/annotations v1.5.0 requires php ^7.1 -> your PHP version (7.0.22) does not satisfy that requirement.
        - dingo/blueprint v0.2.3 requires doctrine/annotations ~1.2 -> satisfiable by doctrine/annotations[v1.5.0].
        - Installation request for dingo/blueprint v0.2.3 -> satisfiable by dingo/blueprint[v0.2.3].
    

    but minimal version of php in composer.json is 7.0.0.

    opened by zhdanovartur 5
  • Refresh token issue

    Refresh token issue

    I found out that here

    $api->group(['middleware' => 'jwt.auth'], function(Router $api){
    
        $api->get('protected', function() {
    
                return response()->json([
                    'message' => 'Access to this item is only for authenticated user. Provide a token in your request!'
                ]);
            });
            $api->get('refresh', [
                'middleware' => 'jwt.refresh',
                function() {
                    return response()->json([
                        'message' => 'By accessing this endpoint, you can refresh your access token at each request. Check out this response headers!'
                    ]);
                }
            ]);
    });
    

    jwt.refresh middleware is inside jwt.auth middleware, so when I try to refresh expired key I'm getting "token_expired" response, I think that refresh route have to be outside jwt.auth middleware group.

    opened by vanushwashere 5
  • How do I change my credentials?

    How do I change my credentials?

    How do I change my credentials? For example, currently it considers email and password, I would like to switch to login and password, how do I do this?

    opened by dhsananias 4
  • CORS not working

    CORS not working

    I've added CORS in the relevant places:

    Kernal.php

    `protected $routeMiddleware = [ 'auth' => \Illuminate\Auth\Middleware\Authenticate::class, 'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class, 'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class, 'can' => \Illuminate\Auth\Middleware\Authorize::class, 'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class, 'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class, 'cors' => \Barryvdh\Cors\HandleCors::class, // HERE

        'jwt.auth' => GetUserFromToken::class,
        'jwt.refresh' => RefreshToken::class,
    ];`
    

    And routes/api.php

    $api->version('v1', ['middleware' => 'cors'], function (Router $api) {

    And I've configured cors to only allow from http://google.com (as a test, to make sure it works)

    config/cors.php

    'supportsCredentials' => false, 'allowedOrigins' => ['http://google.com'], 'allowedHeaders' => ['*'], 'allowedMethods' => ['*'], 'exposedHeaders' => [], 'maxAge' => 0, 'hosts' => [],

    However it's not throwing an error when making requests, like i'd expect it too.

    Am I missing something here?

    opened by aidanbigg 4
  • Laravel 5.4 - Token Signature could not be verified

    Laravel 5.4 - Token Signature could not be verified

    Hi, I'm building an api to authenticate my users through my mobile application The login controller return me the correct token.

    <?php
    
    namespace App\Api\V1\Controllers;
    
    use Symfony\Component\HttpKernel\Exception\HttpException;
    use Tymon\JWTAuth\JWTAuth;
    use App\Http\Controllers\Controller;
    use App\Api\V1\Requests\LoginRequest;
    use Tymon\JWTAuth\Exceptions\JWTException;
    use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
    
    class LoginController extends Controller
    {
        public function login(LoginRequest $request, JWTAuth $JWTAuth)
        {
            $credentials = $request->only(['username', 'password']);
    
            try {
                $token = $JWTAuth->attempt($credentials);
    
                if(!$token) {
                    throw new AccessDeniedHttpException();
                }
    
            } catch (JWTException $e) {
                throw new HttpException(500);
            }
    
            return response()
                ->json([
                    'status' => 'ok',
                    'token' => $token
                ]);
        }
    }
    

    Postman result

    {
      "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjEsImlzcyI6Imh0dHBzOlwvXC9iZXRhZmlsZS5vcmdcL2dpcHNcL3B1YmxpY1wvYXBpXC9hdXRoXC9sb2dpbiIsImlhdCI6MTQ5Mjc4MDI2NiwiZXhwIjoxNDkyNzgzODY2LCJuYmYiOjE0OTI3ODAyNjYsImp0aSI6InZHWkxaNHNqRUlqYW05WTMifQ.g8_-qHsVVvCEj9_BoqDCKJ9QHvm-yqWALsXmxeMK_3c"
    }
    

    Now when I tried to get the current user by token I get the signature error User controller

    <?php
    
    namespace App\Api\V1\Controllers;
    
    use JWTAuth;
    use App\Record;
    use App\Http\Requests;
    use Illuminate\Http\Request;
    use Dingo\Api\Routing\Helpers;
    use App\Http\Controllers\Controller;
    use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
    
    class RecordController extends Controller
    {
        use Helpers;
    
        public function store(Request $request) {
        	//$record = new Record;
        	//return $this->currentUser();
        	$currentUser = JWTAuth::parseToken()->authenticate();
        	return $currentUser;
    
        }
    
        private function currentUser() {
        	return JWTAuth::parseToken()->authenticate();
        }
    }
    
    Postman result
    {
      "error": {
        "message": "Token Signature could not be verified.",
        "status_code": 500
      }
    }
    

    I already try by pass the token by url domain.com/api/auth?token=token_key and by header Authorization Bearer token_key

    Also I have the jwt secret inside config/jwt.php 'secret' => env('jwt_secret') and inside .env JWT_SECRET=jwt_secret

    Any tip to help to solve this issue?

    Thanks

    opened by abolinhas 4
  • Recovery - Authentication Required

    Recovery - Authentication Required

    POST on /auth/recovery returns:

    REQUEST:

    POST /auth/recovery HTTP/1.1
    Content-Type: application/json
    Host: api.dev
    Connection: close
    User-Agent: Paw/2.3.1 (Macintosh; OS X/10.12.1) GCDHTTPRequest
    Content-Length: 35
    
    {"email":"[email protected]"}
    

    RESPONSE:

    {
      "message": "Expected response code 250 but got code \"530\", with message \"530 5.7.1 Authentication required\r\n\"",
      "code": 530,
      "status_code": 500
    }
    

    I'm doing something wrong?

    opened by nerijunior 4
  • Problem with CORS

    Problem with CORS

    @francescomalatesta Hi! Thank you for sharing your project with us!

    I created an application in AngularJS and I'm trying to make calls to the Laravel API: MyApp (AngularJS): http://localhost:8080/ API (Laravel Boilerplate): http://localhost:8000/

    But I get this error in the browser console:

    XMLHttpRequest cannot load http://localhost:8000/api/auth/login. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.

    I tried to apply the cors middleware (barryvdh/laravel-cors) in api_routes.php but the error remains. I am using the Angle Satellizer to login.

    api_routes.php:

    <?php
    
    $api = app('Dingo\Api\Routing\Router');
    
    $api->version('v1', ['middleware' => 'cors'], function ($api) {
    
        $api->post('auth/login', 'App\Api\V1\Controllers\AuthController@login');
        $api->post('auth/signup', 'App\Api\V1\Controllers\AuthController@signup');
        $api->post('auth/recovery', 'App\Api\V1\Controllers\AuthController@recovery');
        $api->post('auth/reset', 'App\Api\V1\Controllers\AuthController@reset');
    
        // example of protected route
        $api->get('protected', ['middleware' => ['api.auth'], function () {     
            return \App\User::all();
        }]);
    
        // example of free route
        $api->get('free', function() {
            return \App\User::all();
        });
    
    });
    
    

    My config/cors.php:

    return [
        'supportsCredentials' => false,
        'allowedOrigins' => ['*'],
        'allowedHeaders' => ['*'],
        'allowedMethods' => ['*'],
        'exposedHeaders' => [],
        'maxAge' => 0,
        'hosts' => [],
    ];
    

    Error: Error Error

    opened by vitalibr 4
  • Two responses

    Two responses

    i am geting two responses when signing up a 200 response and a 201 response the 200 is {status: "ok"} and the 201 is {status: "ok", token: "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjMsI…YzIn0.Kr1UZwp1P1Z84JlQThrb_ewot5kvBTXxWDkNd0cXfad"}

    opened by wyklif 3
  • OpenAPI integration

    OpenAPI integration

    Would be cool to have a OpenAPI integration. Like the one here that I made yesterday: https://crocodile2u.github.io/blog/2020/03/13/laravel-api-boilerplate-jwt-openapi

    opened by crocodile2u 0
  • Reset Password Fails

    Reset Password Fails

    Hi everyone....

    I am facing the an issue when I am trying to do a password reset. I am passing the required parameters in postman body. Upon tracing, I have found that when API is called in response it gets password.passwords instead of getting password.reset. and at the end hits throw new HttpException(500); . I am following all the steps but it seems that something is missing would really appreciate any help on this one.. .

    opened by aidataguy 4
Owner
Francesco Malatesta
Developer @ AdEspresso, Founder @ Laravel-Italia, Editor @ Sitepoint. Developer, Curious, Enthusiast
Francesco Malatesta
Laravel 8 boilerplate in docker-compose with Treafik and SSL setup and github workflow ready for CI/CD pipeline

Laravel8 boilerplate Laravel 8 boilerplate in docker-compose with Treafik and SSL setup with .github workflow ready To start the containers in prod en

Tej Dahal 5 Jul 9, 2022
The Laravel Boilerplate Project - https://laravel-boilerplate.com

Laravel Boilerplate (Current: Laravel 8.*) (Demo) Demo Credentials Admin: [email protected] Password: secret User: [email protected] Password: secret Offici

Anthony Rappa 5.4k Jan 4, 2023
Rest API boilerplate for Lumen micro-framework.

REST API with Lumen 5.5 A RESTful API boilerplate for Lumen micro-framework. Features included: Users Resource OAuth2 Authentication using Laravel Pas

Hasan Hasibul 484 Sep 16, 2022
WP React Plugin Boilerplate - WordPress Setting via React and Rest API

WP React Plugin Boilerplate is a starter WordPress plugin to develop WordPress Plugin via React and Rest API. WP React Plugin Boilerplate WP React Plu

Santosh Kunwar 36 Dec 6, 2022
Api first backend boilerplate build with laravel 🎯 you can use as a template 😉

Laravel Backend Template i use this as a starting point for my backend projects , it saves time with basic auth functionalities and has code examples

Hijen EL Khalifi 4 Nov 14, 2022
Production Ready, Carefully Crafted, Extensive Vuejs Laravel Free Admin Template 🤩

Materio - Vuetify VueJS Laravel Free Admin Template Production ready carefully crafted most comprehensive admin template Introduction If you’re a deve

ThemeSelection 115 Dec 13, 2022
Fluent Interface for Laravel Backpack - Define resources once and get all CRUD configurations ready!

CRUD Resource for Laravel Backpack This package allows creating CRUD panels for Backpack for Laravel administration panel using fluent field definitio

FigLab 8 Nov 20, 2022
Hydra is a zero-config API boilerplate with Laravel Sanctum that comes with excellent user and role management API out of the box

Hydra - Zero Config API Boilerplate with Laravel Sanctum Hydra is a zero-config API boilerplate with Laravel Sanctum and comes with excellent user and

Hasin Hayder 858 Dec 24, 2022
Kick-start you next Laravel based API with this awesome boilerplate 🚀

Laravel API boilerplate ?? An awesome boilerplate for your next Laravel 9 based API. It's only goal is to simply kick-start your API development and p

treblle 130 Dec 23, 2022
Boilerplate between the Magento API and ImportExport, so that you can do fast Array/XMLRPC/SOAP based product imports.

Boilerplate between the Magento API and ImportExport, so that you can do fast Array/XMLRPC/SOAP based product imports.

Daniel Sloof 249 May 30, 2022
LaraAdmin is a Open source Laravel Admin Panel / CMS which can be used as Admin Backend, Data Management Tool or CRM boilerplate for Laravel with features like Advanced CRUD Generation, Module Manager, Backups and many more.

LaraAdmin 1.0 LaraAdmin is a Open source CRM for quick-start Admin based applications with features like Advanced CRUD Generation, Schema Manager and

Dwij IT Solutions 1.5k Dec 29, 2022
A Laravel 5 package that switchs default Laravel scaffolding/boilerplate to AdminLTE template and Pratt Landing Page with Bootstrap 3.0

AdminLTE template Laravel package A Laravel package that switch default Laravel scaffolding / boilerplate to AdminLTE template with Bootstrap 3.0 and

Sergi Tur Badenas 1.8k Jan 3, 2023
High scalable boilerplate for Laravel - Vue using laravel-mix.

Why use this ? This boilerplate make developer easier to make monolith Laravel project which integrated with Vue.js and vue-router as default front-en

Carvel Saputra Martaloho 5 Sep 21, 2022
Laravel and AngularJS Starter Application Boilerplate featuring Laravel 5.3 and AngularJS 1.5.8

?? Zemke/starter-laravel-angular has been upgraded to AngularJS 1.5.8. ?? Zemke/starter-laravel-angular has been upgraded to Laravel 5.3. You can pull

Florian Zemke 372 Nov 21, 2022
Laravel Boilerplate (Current: Laravel 8.*)

Laravel Boilerplate (Current: Laravel 8.*) (Demo) Demo Credentials Admin: [email protected] Password: secret User: [email protected] Password: secret Offici

Anthony Rappa 5.2k Nov 17, 2021
Laravel Quick-Start - a boilerplate for Laravel Application with typical packages preinstalled and configured

Laravel Quickstart is a boilerplate for Laravel Application with typical packages preinstalled and configured to extend a full-fledged application. We tried to make it as minimal as possible.

Vijay Goswami 18 Sep 8, 2022
Creating a simple weather web application with Laravel rest API.

Weather Channel Creating a website for weather status, with Laravel restAPI. See the Website Weather.Channel-1.mov Features REST API Invoake Controlle

AmirH.Najafizadeh 3 Jul 31, 2022
Technical test from a company - Laravel 8 | REST Api | Livewire | Boostrap

Contacts CRUD (Laravel 8) (Demo) Introduction A simple CRUD for manage contacts using Laravel 8. All transaccions work through an REST API. Tech stack

Sebastian Sperandio 3 Nov 17, 2022
A Laravel REST API backend with React/Redux, hot module reloading in development and route-level code splitting

React Laravel Boilerplate This is the boilerplate that I personally use for getting projects off the ground quickly using my favourite stack of techno

Carwyn Stephen 174 Jan 6, 2023