0
votes

Until now I have only used my Laravel app as a backend API to my mobile app. The user logs in and get a token that then is stored on the device, then the device use that basic http token on each request to my backend API.

But now I am building a web based version of my app. I want to send a POST update in my page using axios and vue, but I am not sure how I should do this since my route is protected by auth.

Should I do something like this?:

<your-component :auth_user="{{auth()->user()->api_token}}"></your-component>

Or simply create a meta:

<meta name="token" id="token" value="{{ auth()->check() ? auth()->user()->api_token : null }}">

This way my component gets my users api_token which can later be used in axsios when I send a post request using a basic http auth.

Or what is the common way to talk to a protected API using axios?

thanks

1
I think the 2nd method is fine. However, if you're authenticating only the api, you should specify that guard, auth()->guard('api')->check() ? auth()->guard('api')->user()->api_token. If you are not using the api guard, ignore me.Ohgodwhy

1 Answers

0
votes

Laravel have a good package for API authentication called Passport , so after configured, it create the routes for require and return the token. To request it's http://{domain}/oauth/token.

When the user try to log in, Vue must send a post request with axios passing the user data. If the user have access, the token it's returned.

To protect your routes you can use middleware('auth:api'). Passport uses this middleware to validate the token.

ie:

<script>
  userData = {
    ...
  },
  axios.post('http://{domain}/oauth/token', userData) {
    .then(function (response) {
      console.log(response.access_token)
      ... redirect to dashboard or something else
    }
  }
  ...
  </script>

As you may know, the token has to be passed in every client request, and a way to do this is passing the token in the HTTP request header. Fortunately Passport already do this for you.

Hope it helps.