0
votes

I have a project with Laravel to manage the endpoint calls and Vue to control frontend.

When user do a login the response (a token) saved in the localStorage,then in app.js i add this token automatically to all calls.

Login

  axios
        .post("http://127.0.0.1:8000/api/login", {
          username: this.username,
          password: this.password
        })
        .then(response => {
          if (response.data.token != null) {
            localStorage.setItem("token", response.data.token);
            //PUSH SECOND PAGE
          }
        })

App.js

const token = localStorage.getItem('token')

if (token) {
    axios.defaults.headers.common['Authorization'] = "Token " + token
}

Now, we´ll see the problem.

When we go to the second page a endpoint call will be launch automatically to fill some inputs. This call theoretically have a localStorage token.

 mounted() {
    axios
      .get("http://127.0.0.1:8000/api/elements")
      .then(response => {
        console.log(response.data);
      })
      .catch(function(error) {
        console.log(error);
      });
  }

Routes (API endpoints)

Route::get('elements', 'HeaderController@elements')->name('header.elements');

HeaderController

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;

class HeaderController extends Controller
{
    public function elements()
    {
        $response = Http::get('API');
        return $response->json();
    }
}

This returns Access Denied. The token is informed in the header.

Is curious but if we call directly to the API through Axios response will be correct, but if we use a Laravel endpoint return this Access Denied.

So: Anybody see the error? Why axios returns right response but Laravel return 403?

UPDATE 1

LoginController Laravel Class

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
//use Illuminate\Foundation\Auth\AuthenticatesUsers;

use App\Http\Requests\LoginRequest;

use Illuminate\Support\Facades\Http;

class LoginController extends Controller
{
   // use AuthenticatesUsers;

    protected $redirectTo = RouteServiceProvider::HOME;

   /* public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }*/

    public function login(LoginRequest $request)
    {
        $response = Http::post('API', [
            'username' => $request->username,
            'password' => $request->password,
        ]);
        return $response->body();
    }
}

UPDATE 2 (Ignore this i fix it)

When i call API trough Axios has

Content-Type: application/json

if i use Laravel endpoint has

Content-Type: text/html; charset=UTF-8

UPDATE 3

Array i expected in Endpoint response

{
    "code": 0,
    "message": "",
    "body": [
        {
            "id": 1,
            "entity": "Test1",
            "agrupations": [
                {
                    "id": 6,
                    "name": "A"
                },
                {
                    "id": 7,
                    "name": "B"
                }
            ]
        },
        {
            "id": 2,
            "entity": "Test2",
            "agrupations": [
                {
                    "id": 8,
                    "name": "C"
                },
                {
                    "id": 9,
                    "name": "D"
                }
            ]
        },
        {
            "id": 3,
            "entity": "Test3",
            "agrupations": [
                {
                    "id": 1,
                    "name": "E"
                },
                {
                    "id": 11,
                    "name": "F"
                }
            ]
        },
        {
            "id": 4,
            "entity": "Test4",
            "agrupations": [
                {
                    "id": 10,
                    "name": "G"
                }
            ]
        }
    ]
}

UPDATE 4

I comments auth route to avoid routes conflicts

Web.php

//Auth::routes();

enter image description here

UPDATE 5

Full cURL.

Mmmm, maybe Laravel X-XSRF-TOKEN and SRF-TOKEN 'broke' something.

This doesn´t work (Using Laravel for Endpoint)

curl 'http://127.0.0.1:8000/api/elements' -H 'Connection: keep-alive' -H 'DNT: 1' -H 'X-XSRF-TOKEN: eyJpdiI6IjV4aU9qOXpaY2FoLytIQ1RTSi9jZGc9PSIsInZhbHVlIjoiWTlmOUcwL21Ld0xVYXZwdWZyVDJhVktzczlJSzVtdHE2UUsvREp3Nm51RjBZYStaaXptYmx0N0F0bzVkWTQvQiIsIm1hYyI6IjE3OWFiOGU5ZjFjZDhhMDc4OTUzYmJjZDUxZWYwMWY3MzgyOTg3YjM0MjFlNjk5MTc0MGExZDNmYmQ2YzIzY2IifQ==' -H 'Authorization: Token eyJhbGciOiJIUzUxMiJ9.eyJpYXQiOjE1ODUxNTYzMjgsImlzcyI6Imh0dHBzOi8vd3d3LmFyc29uLmNvbS8iLCJzdWIiOiJhbGFyYSIsImV4cCI6MTU4NjAyMDMyOH0.Mv968xR4IAdbkgqABvg2CLNxSc6mkFPxqEKm9VbbFYOg-H5Ppo80DEsoj8F8pT2yoY7LHF5P_zMbWymAwxPzvQ' -H 'Accept: application/json, text/plain, /' -H 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36' -H 'Sec-Fetch-Dest: empty' -H 'X-Requested-With: XMLHttpRequest' -H 'Sec-Fetch-Site: same-origin' -H 'Sec-Fetch-Mode: cors' -H 'Referer: http://127.0.0.1:8000/lora/' -H 'Accept-Language: es-ES,es;q=0.9,en;q=0.8' -H 'Cookie: XSRF-TOKEN=eyJpdiI6IjV4aU9qOXpaY2FoLytIQ1RTSi9jZGc9PSIsInZhbHVlIjoiWTlmOUcwL21Ld0xVYXZwdWZyVDJhVktzczlJSzVtdHE2UUsvREp3Nm51RjBZYStaaXptYmx0N0F0bzVkWTQvQiIsIm1hYyI6IjE3OWFiOGU5ZjFjZDhhMDc4OTUzYmJjZDUxZWYwMWY3MzgyOTg3YjM0MjFlNjk5MTc0MGExZDNmYmQ2YzIzY2IifQ%3D%3D; lorawan_session=eyJpdiI6IjZEa1ZQWkY1ZHhYamxPaUxSWGFvdUE9PSIsInZhbHVlIjoiaGltclROWnZPTWR4TWZZa3VzcUU4ekZjUklUUWlSNGo5U1pPM1ZLcVpJU0NoVS9ma1hmTS9reW1ENWNWMHJNcSIsIm1hYyI6ImUyYWVkZmUxYTk2M2IzMWQ5MTkyY2RkYzZjZDA3N2U5YTdjNDhiYzliNGQzZjEzOGYzMjFiODJhZWFlMjE3ODcifQ%3D%3D' --compressed

This work (Using Axios to call directly API)

curl "API" -H "Connection: keep-alive" -H "Accept: application/json, text/plain, /" -H "Sec-Fetch-Dest: empty" -H "X-Requested-With: XMLHttpRequest" -H "Authorization: Token eyJhbGciOiJIUzUxMiJ9.eyJpYXQiOjE1ODUxNTcyODksImlzcyI6Imh0dHBzOi8vd3d3LmFyc29uLmNvbS8iLCJzdWIiOiJhbGFyYSIsImV4cCI6MTU4NjAyMTI4OX0.9MfXYgBDhYltmbfz7rwFWhL0dQUFFRO43ioK8cVlM2C1_-9GolXeC9e55hEclmP4bTuGWfS5HOj9SOWXiDowLA" -H "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36" -H "DNT: 1" -H "Origin: http://127.0.0.1:8000" -H "Sec-Fetch-Site: cross-site" -H "Sec-Fetch-Mode: cors" -H "Referer: http://127.0.0.1:8000/lora/" -H "Accept-Language: es-ES,es;q=0.9,en;q=0.8" --compressed

1
The issue will be at your authorization layer. How are you authenticating users? Are you meant to send the header as 'Token abc...' or 'Bearer abc...'?James
Does your internal Http::post('API', [...]) request require authentication? You might need to forward the Authorization-header there as well.Christoph Kluge
Why would it be necessary to add the token in Laravel? I'm already adding it globally in App.js, I try too get App.js const token and pass to the endpoint but i don´t know how can i get it.El Hombre Sin Nombre
I update question.El Hombre Sin Nombre
@ElHombreSinNombre your LoginController seems to Proxy-Forward your request to another api call, that's the reason. Anyway according to you updated question: Can you add Accept: application/json header to you axios request? This will tell laravel that you are only accepting json responses. Otherwise laravel might return an text/html if you'll encounter an error inside laravel.Christoph Kluge

1 Answers

0
votes

Update your axios header to a Bearer token.

axios.defaults.headers.common['Authorization'] = "Bearer " + token

https://laravel.com/docs/6.x/api-authentication#passing-tokens-in-requests