Mena
Mena

Reputation: 2029

Returning response when user is unauthorised in Laravel

When a user is not authenticated, Laravel redirects all request made to routes using auth::api middleware to the default laravel login page. However since I am building the API only, I want to return a 401 unauthorised response to any app that will be consuming my api. This should be simple but for some reason, I haven't been able to do just that. Here's what my code looks like

public function show(User $user)
{
    if ($user->id == auth()->user()->id) {

        // do something here
    } else {

         return response()->json([ 'status_message' => 'Unauthorised'], 401);
     }
}

public function update(Request $request, User  $user)
{
    if ($user->id == auth()->user()->id) {

        // do something here
    } else {

        return response()->json(['status_message' => 'Unathorised'], 401);
    }
}

When I hit the endpoints calling these methods and the user isn't authenticated, I am redirected to the default laravel login page. How can I override this default behavior?

Upvotes: 2

Views: 1631

Answers (2)

Mena
Mena

Reputation: 2029

Problem solved guys. Here's how I did it, in the Handle.php file in app\Exceptions\ I added this code to the render function

if ($exception instanceof AuthenticationException) {
    return response()->json(['status_message' => 'Unauthorised'], 401);
}

And that was it.

Note: this worked in laravel 5.8

Upvotes: 1

Roshni hegde
Roshni hegde

Reputation: 415

Call api.auth middleware in your routes as follows

  $api->group(['middleware' => 'api.auth'], function ($api){
     //your routes  
  });

Create a file Authenticate.php inside Middleware folder

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Contracts\Auth\Factory as Auth;
class Authenticate {
    /**
     * The authentication 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(Auth $auth)
    {
        $this->auth = $auth;
    }

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string|null  $guard
     * @return mixed
     */
    public function handle($request, Closure $next, $guard = null)
    {
        if ($this->auth->guard($guard)->guest()) {
            return response('Unauthorized.', 401);
        }

        return $next($request);
    }

}

and in kernel.php which is inside http folder include the following

protected $routeMiddleware = [
        'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
   ];

Upvotes: 1

Related Questions