dingo / api

A RESTful API package for the Laravel and Lumen frameworks.
BSD 3-Clause "New" or "Revised" License
9.33k stars 1.25k forks source link

Illuminate\Auth\Access\AuthorizationException is thrown with status 500 instead of 401 #1764

Closed ivancli closed 3 years ago

ivancli commented 3 years ago
Q A
Bug? yes
New Feature? no
Framework Laravel
Framework version 8.18.1
Package version 3.0.5
PHP version 7.4.12

User Case

Sending a post request to an auth:api protected endpoint as a guest.

Actual Behaviour

Return unauthenticated as error message but with status 500

Expected Behaviour

Return unauthenticated as error message with status 401

Possible Solutions

Handle Illuminate\Auth\Access\AuthorizationException is handled specifically by Laravel to respond with status 401. Dingo shall probably handle that exception the same way to keep the behaviour consistent.

gazben commented 3 years ago

I had to override the Authenticate middleware to get the normal response

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string[]  ...$guards
     * @return mixed
     *
     * @throws \Illuminate\Auth\AuthenticationException
     */
    public function handle(Request $request, Closure $next, array ...$guards)
    {
        try {
            $this->authenticate($request, $guards);
        } catch (AuthenticationException $authenticationException) {
            return redirect()->to($authenticationException->redirectTo());
        }

        return $next($request);
    }