If you need to integrate your GitHub repositories with your Laravel 5 application, you are in the right place. We will be implementing GitHub webhooks in Laravel 5 using Secret token as authentication method.
For this example I’ll be creating a new config file for simplicity, but you can use any of your config files.
Instructions:
In your /config folder add the file github.php with the following content:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<?php return [ /* |-------------------------------------------------------------------------- | Token used to validate requests from github webhooks |-------------------------------------------------------------------------- | */ 'webhook-secret-token' => 'your-github-secret-key-here', ]; |
In the folder /App/Http/Middleware add the file GitHubSecretTokenMiddleware.php with the following content:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
<?php namespace App\Http\Middleware; use Auth; use Config; use Closure; use App\User; class GitHubSecretTokenMiddleware { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { $sig_check = 'sha1=' . hash_hmac('sha1', $request->getContent(), Config::get('github.webhook-secret-token')); if ($sig_check !== $request->header('x-hub-signature')) return response(['error' => 'Unauthorized'], 401); //Do you stuff return $next($request); } } |
Add the new middleware to the $routeMiddleware array in /app/Http/Kernel.php , should look like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<?php namespace App\Http; use Illuminate\Foundation\Http\Kernel as HttpKernel; class Kernel extends HttpKernel { /** * The application's route middleware. * * @var array */ protected $routeMiddleware = [ 'auth' => \App\Http\Middleware\Authenticate::class, 'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class, 'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class, 'github.secret.token' => \App\Http\Middleware\GitHubSecretTokenMiddleware::class, ]; } |
Finally add your routes using the github webhook middleware in your routes.php file
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<?php /* |-------------------------------------------------------------------------- | Application Routes |-------------------------------------------------------------------------- | | Here is where you can register all of the routes for an application. | It's a breeze. Simply tell Laravel the URIs it should respond to | and give it the controller to call when that URI is requested. | */ Route::get('/', function () { return view('welcome'); }); Route::post('api/github', ['middleware' => 'github.secret.token', 'uses' => 'GitHubController@gitHubUpdate']); |
Enjoy!