Get fresh content from StatelyWorld

In many modern applications, especially those built with Flutter or mobile frameworks, we often need to authenticate users via an API and then open a WebView that should already have the user logged in. Instead of duplicating login steps, we can auto-login users in Laravel using a secure token passed in the URL and a middleware to handle the logic.

Goal

When a user logs in through the API, Laravel generates a secure token. This token is appended to a URL that is opened inside a WebView. Laravel should detect the token and authenticate the user automatically using middleware.

Why Middleware?

Middleware allows us to intercept HTTP requests and apply logic like authentication globally or on specific routes. Using a middleware for auto-login via token is a clean and reusable solution.

Avoid Using remember_token

Do not use Laravel’s remember_token for API authentication. It is intended for “Remember Me” functionality and is not secure for cross-platform login via URLs.

Recommended Approach Using Sanctum Token

Instead of remember_token, use Laravel Sanctum tokens, which are hashed and secure. Below is a custom middleware that authenticates a user based on a Sanctum token passed as a query parameter.

Step 1: Create Middleware

php artisan make:middleware AutoLoginTokenMiddleware

Step 2: Implement Logic in Middleware

<?php

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class AutoLoginTokenMiddleware
{
    public function handle(Request $request, Closure $next)
    {
        if ($request->has('token')) {
            $token = $request->get('token');

            // Extract plain part of token
            $plainToken = explode('|', $token)[1] ?? null;

            if (!$plainToken) {
                throw new \Exception('Invalid token format');
            }

            $user = \App\Models\User::whereHas('tokens', function ($query) use ($plainToken) {
                $query->where('token', hash('sha256', $plainToken));
            })->first();

            if ($user) {
                Auth::login($user);
                return redirect(RouteServiceProvider::HOME);
            } else {
                throw new AuthenticationException('Invalid token.');
            }
        }

        return $next($request);
    }
}

 

Step 3: Register Middleware

  // In app/Http/Kernel.php

  protected $routeMiddleware = [
      'token.login' => \App\Http\Middleware\AutoLoginTokenMiddleware::class,
  ];

Step 4: Apply Middleware to Routes

  Route::middleware(['web', 'token.login'])->group(function () {
      Route::get('/dashboard', [DashboardController::class, 'index']);
  });

Security Best Practices

  • Always use hashed tokens via Laravel Sanctum.
  • Consider using URL::temporarySignedRoute to generate time-limited, tamper-proof URLs.
  • Regenerate sessions after login to prevent session fixation.
  • Optional: Expire the token after one-time use for better security.

Conclusion

Auto-login via a token using middleware is a clean and secure way to authenticate users in a Laravel WebView after API login. Avoid using remember_token and rely on hashed Sanctum tokens. By handling this in middleware, your logic remains reusable, organized, and easy to maintain.

How to Run Laravel Scheduler Automatically on Windows (Herd or XAMPP)
How to Build and Publish a Laravel Package on Packagist

Share This Post !

Leave A Comment