dingo / api

A RESTful API package for the Laravel and Lumen frameworks.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

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

ivancli opened this issue · comments

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.

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);
    }