🤹
TALL Stack Tips
  • What is TALL Stack
  • Tailwind
    • Tailwind Resources
    • Swinging Bell Notification Icon
    • Styled Unordered Lists
  • Alpine
  • Alpine Resources
  • Tabbed Content Using Alpine JS
  • Checkbox component with SVG tick
  • Dropdown animation
  • Create a Sliding Puzzle Captcha
  • Laravel
    • Tabler Icons Component
    • Password-less Login with Laravel 8+
    • Password-less Login with Magic Link in Laravel 8
    • Laravel Resources
    • Laravel Breeze Login Conditional Redirect
    • Jetstream Login Conditional Redirect
    • Simplify Laravel CRUD Controllers
    • CSRF and expired login forms
    • CSRF and expired logout forms
    • Add your own logo to Laravel Mail
    • Specify a different mail theme for Notifications
    • Show custom page when email verification link expired
    • Using a mutator to save currency
    • Using Spatie Valuestore to hold frequently accessed settings
    • Using the old() helper
    • Alternatives to using Eloquent Accessor
    • UpdateOrCreate may not update timestamp
    • Use of lockForUpdate()
    • Using S3
    • Super Simple User Based Feature Flags
    • Installing a Specific Version of Laravel
    • Versioning your Laravel Project
    • CSS Cache Busting with your Git Commit SHA
    • Adding column to Database Notifications table
    • Find nearby locations using the Haversine formula in Eloquent query
    • Using Queues on Shared Hosting with Laravel
    • Create Guaranteed Unique Invoice Number in Laravel
    • Send Notification to all team members
    • Protect Staging site with Basic Auth
    • Working with Enums
    • PHP DateTime formatting cribsheet
  • Livewire
    • Livewire Resources
    • Naming Livewire Components
    • Dynamic Cascading Dropdown with Livewire
    • Hiding a button after click
    • Working with Javascript Components
    • SweetAlert2 with Livewire
    • Select Multiple or Checkboxes
    • Clearing checkboxes in Livewire
    • Livewire File Uploads Using S3
    • Simple Log File Viewer
  • Related Resources
    • Testing resources
    • When Composer runs out of memory
    • Deployment
    • Security
    • Scheduler & Cron tips
    • LastPass tips
    • Using Git
    • VSCode Tips
    • Markdown
    • Cpanel resources
Powered by GitBook
On this page
  • Create a middleware
  • Add middleware to the 'web' group
  • Setting Credentials
  • Clearing Basic Auth credentials in Chrome

Was this helpful?

  1. Laravel

Protect Staging site with Basic Auth

When you don't want public sites crawling

If you have a staging instance of your website, it will probably look just like your production server and have all the same pages.

This can cause your production site to be penalised by search engines (because of duplicate content) or potential confusion by customers who happen upon your staging site when then actually want production.

A simple solution is to add basic authentication when the site's environment is `staging`.

Create a middleware

I called this StagingBasicAuth, you can choose this name or whatever makes sense to you

App\Http\Middleware\StagingBasicAuth.php
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\App;
use Illuminate\Contracts\Auth\Factory as AuthFactory;


class StagingBasicAuth
{
        /**
         * The guard factory instance.
         *
         * @var \Illuminate\Contracts\Auth\Factory
         */
        protected $auth;
    
        /**
         * Create a new middleware instance.
         *
         * @param  \Illuminate\Contracts\Auth\Factory  $auth
         * @return void
         */
        public function __construct(AuthFactory $auth)
        {
            $this->auth = $auth;
        }
    
        /**
         * Handle an incoming request.
         *
         * @param  \Illuminate\Http\Request  $request
         * @param  \Closure  $next
         * @param  string|null  $guard
         * @param  string|null  $field
         * @return mixed
         *
         * @throws \Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException
         */
        public function handle($request, Closure $next, $guard = null, $field = null)
        {
            if(App::environment() == 'staging') {
                $this->auth->guard($guard)->basic($field ?: 'email');
            }
            
            return $next($request);
        }
    }
    

```

If the app environment is NOT staging then the middleware is skipped and has no effect

Add middleware to the 'web' group

Add the middleware to the array of $middlewaregroups (Laravel 10) / $routeMiddleware (earlier).

            \App\Http\Middleware\StagingBasicAuth::class,
            

When APP_ENV = staging no content from the site will be accessible without first logging in.

Setting Credentials

By default, the basic authentication guard will validate the user against the users table with the email field and hashed password.

Clearing Basic Auth credentials in Chrome

Whilst testing this, you may come across an issue where Chrome (and possibly others) refuse to logout from the site since as soon as you access the site it sends the cached credentials. The only reliable method I have found to clear the credentials is to add a route to your site like;

Route::get('/clearbasic', function() { auth()->logout(); abort(401);});

Hit this route and Chrome will forget what it thinks are invalid credentials. You can then revisit the site and be re-prompted for the login.

PreviousSend Notification to all team membersNextWorking with Enums

Last updated 8 months ago

Was this helpful?