PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, January 12, 2022

[FIXED] How to return unauthorized using Laravel API Authentication

 January 12, 2022     api, laravel     No comments   

Issue

I am using Laravel API authentication with a token. (as explained here: https://laravel.com/docs/5.8/api-authentication#protecting-routes)

I am running some tests with Postman and it works fine. When I try to access the route without a valid token, I see that the response is the (html of the) login page of my app. How can I return a Unauthorized message instead of the complete login page? Do I have to create a custom middleware?

Controller

class ExampleController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth:api');
    }

    public function show(Request $request) {
        return response()->json($request->user()->name);
    }
 }

Solution

Please add the method in the class Handler in the file location app/Exceptions/Handler.php

/**
 * Convert an authentication exception into an unauthenticated response.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Illuminate\Auth\AuthenticationException  $exception
 * @return \Illuminate\Http\Response
 */
protected function unauthenticated($request, AuthenticationException $exception)
{
    if ($request->expectsJson()) {
        return response()->json(['error' => 'Unauthenticated.'], 401);
    }

    return redirect()->guest(route('login'));
}

And also add the following line above the class in the same file as mentioned above: use Illuminate\Auth\AuthenticationException;

In the postman within the headers section please add the following header : X-Requested-With:XMLHttpRequest

Hope this helps and resolves the issue. Thanks.



Answered By - Saibal Roy
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing