user742736
user742736

Reputation: 2729

Laravel 7: How to prevent middleware Authenticate from redirecting when user is not authenticated?

I have implemented the middleware Authenticate with $this->middleware('auth:api');.

The application is a REST API so I don't need Laravel to redirect the client. I need it to return a JSON response.

There is a method redirectTo inside App\Http\Middleware\Authenticate.php;. This method only accepts a route, therefore I cannot add the JSON response to this method.

How can I use the middleware Authenticate (auth:api) and return a JSON Response when the user is not authenticated?

Upvotes: 2

Views: 7081

Answers (2)

patricus
patricus

Reputation: 62228

Laravel already does this when the request expects a JSON response. So, as long as you're either sending AJAX requests or you're sending requests with the Accept header set properly (application/json or *), Laravel will automatically respond with a 401 JSON response.

Upvotes: 7

Ersoy
Ersoy

Reputation: 9586

<?php

namespace App\Http\Middleware;

use Illuminate\Auth\Middleware\Authenticate as Middleware;

class Authenticate extends Middleware
{
    /**
     * Get the path the user should be redirected to when they are not authenticated.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return string|null
     */
    protected function redirectTo($request)
    {
        if (! $request->expectsJson()) {
            return route('login');
        }
    }
}

This class is extending Illuminate\Auth\Middleware\Authenticate - and it overrides redirectTo method. You need to write down your own handle method. If you want you may remove extends part if you don't need framework's authenticate method.

public function handle($request, Closure $next, ...$guards)
{
    if (Auth::guest()) {
        return response()->json(['message' => 'you shall not pass']);
    }

    // other checks

    return $next($request);
}

Another option would be keeping the extends and calling parent method after doing your regular checks if you need some of the functionality from base class.

public function handle($request, Closure $next, ...$guards)
{
    if (Auth::guest()) {
        return response()->json(['message' => 'you shall not pass']);
    }

    return parent::handle($request, $next, $guards);
}

Upvotes: 4

Related Questions