ReynaMoon
ReynaMoon

Reputation: 311

Laravel api authenticates POST requests but returns 'Unauthenticated' with GET

I have setup a Route group to authenticate my API calls with a token.

POST requests work fine, valid token passes authentication and an invalid one returns "Unauthenticated" as expected.

When making a GET request I get "Unauthenticated" every time.

I'm making GET requests with the same api_token that I made the POST requests with and still get "Unauthenticated"

This is my route group

Route::group(['middleware' => ['auth:api', 'api']], function () {
    Route::post('/', 'ApiPostController@store');
    Route::get('/', 'ApiPostController@fetch');
});

I tried removing the POST route from the group, that didn't work. Tried changing the route (from / to /get) that didn't do anything either.

What is causing the GET requests to fail even though I'm sending a valid token?

Upvotes: 0

Views: 491

Answers (2)

V-K
V-K

Reputation: 1347

The problem is you send api_token in body and the request body is different for GET and POST requests. Also sending tokens in the GET body is insecure, that's why you have to send tokens via headers.

Upvotes: 3

Md Asaduzzaman
Md Asaduzzaman

Reputation: 99

If you are in Apache server you can try adding those line in .htaccess

RewriteEngine On
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]

you can also clear config and try

php artisan config:clear

you can add @csrf as well.

Upvotes: 1

Related Questions