0

I'm using Laravel for backend and AngularJS for handle the front-end. The problem is the angularjs call ajax to controller to get the data, otherwise the auth middleware, i want to add 1 more middleware called apiKeyAuth to check if end user send request with valid api key. But after i check the conditional inside apiKeyAuth, it give me an error in \Http\Middleware\VerifyCsrfToken.php. The return type of invalid api key is an array. Below is my code.

*APIKeyAuth Middleware:

class APIKeyAuth
{
    public function handle($request, Closure $next)
    {
        if ($request->get('api_key') != 'MyAPIKey'){
            return ['status' => 401, 'message' => 'Invalid API Key.', 'data' => null];
        }
        return $next($request);
    }
}

2 Answers 2

2

You should return a JsonResponse instead of an array:

class APIKeyAuth
{
    public function handle($request, Closure $next)
    {
        if ($request->get('api_key') != 'MyAPIKey'){
            return Illuminate\Http\JsonResponse::create(
                ['message' => 'Invalid API Key.'],
                Illuminate\Http\JsonResponse::HTTP_UNAUTHORIZED
            );
        }
        return $next($request);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

The VerifyCsrfToken middleware checks for a valid csrf token. It runs before your custom middlewares.

By default, your ajax requests don't include an csrf token.

If you make requests from your frontend, simply add a csrf token to your requests. E.g. Axios:

window.axios = require('axios');

window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

let token = document.head.querySelector('meta[name="csrf-token"]');

if (token) {
    window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
} else {
    console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token');
}

If you want to access your api from outside your frontend, consider moving your api routes into the dedicated routes/api.php file or disabling csrf protection on these routes: Docs

namespace App\Http\Middleware;

class VerifyCsrfToken extends Middleware
{
    protected $except = [
        'stripe/*',
        'http://example.com/foo/bar',
        'http://example.com/foo/*',
    ];
}

Also, as @matei-mihai suggested, use JsonResponse to return your array

2 Comments

But i want to be an array to response to my ajax call then i will show the alert, not show new page...@@
Yes, a JsonResponse converts your array to a response. See laravel.com/docs/5.8/responses#json-responses

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.