Search code examples
laravelapi-design

Consuming API of certain endpoints using Vue Components within Laravel Application


I have been browsing for a while to find a viable solution.

I have a Laravel application where I have certain endpoints in API route.

I would like to consume the data without needing to log into application itself. I would appreciate if some body can guide me in the right direction. I have looked into Passport, however I wouldn't like to pass certain information like client_id or client_secret in ajax calls as they can easily be seen.


Solution

  • Here is my 2 cents approach to the problem I was facing. might help some one in the future.

    After quite a bit of research and understanding how JWT works which by the way I still need to research a bit more to fully understand it. However, to get an overview I can't find a better article to explain in simple words other than https://scotch.io/tutorials/the-anatomy-of-a-json-web-token.

    Now, once I understood how JWT works, it was easy for me to wrap my head around the whole flow. So here is how I approached it. As I am working on an internal API for my company, I created a middleware to check whether a request to certain endpoints is coming from whitelisted API which you can easily get from $request->api().

    Then I installed the excellent package by tymondesigns at https://github.com/tymondesigns/jwt-auth. I followed the installation and generated the secret key. Now here comes the fun part.

    I wanted the end points to be secured without needing for me to be logged in, hence I created my own middleware where I grabbed certain user from my users table and created a JWT token from that user object.

    $user = App\User::whereEmail('email')->first() $token = JWTAuth::fromUser($user);

    once I got the token all I needed to do was to call my end point i.e. /api/v1/users?token={generatedToken} and voila !!! all good to go. However, we also need to refresh the token after certain time, which again the package thankfully provide two middlewares

    jwt.auth and jwt.refresh

    jwt.auth midleware tries to create token using authenticate method through credentials, so i swapped it for my middleware where I authenticate user as above and jwt.refreshes the token.

    If you read the article I mentioned and then read the package wiki it will all make sense. Cheerio !!