Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make my middleware respond with a json object if I use an API route

I'm building my first API with Laravel and I'm using JWT for authentication. I don't really understand guards all that well yet but I think I managed to guard my User class. So when I try to reach a route in my UserController it get's guarded and the Authenticate middleware gets called if the user is no authenticated. The problem is that when I try to use the API route via Postman that I get the following error

ErrorException: Header may not contain more than a single header, new line detected in file

namespace App\Http\Middleware;

use Illuminate\Auth\Middleware\Authenticate as Middleware;

class Authenticate extends Middleware
{
    protected function redirectTo($request)
    {
         if (!$request->expectsJson()) {
            return response()->json(['message' => 'Unauthorized'], 403);
         }
    }
}

api.php

<?php
use Illuminate\Support\Facades\Route;

Route::post('register', 'AuthController@register');
Route::get('user/{id}', 'UserController@index');
like image 710
Michael Avatar asked Jan 16 '20 11:01

Michael


Video Answer


1 Answers

You could use:

abort(response()->json('Unauthorized', 403));
like image 110
N. Djokic Avatar answered Sep 16 '22 15:09

N. Djokic