Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

noleafclover614@gmail.com's avatar

API Auth

If I am building a standard MVC app with an API that I only plan on using for some simple Vue AJAX calls, do I need to worry about authentication? That is, can I simply rely on the normal Laravel authentication scheme and protect the API routes with the normal auth middleware?

0 likes
9 replies
mehany's avatar

@noleafclover614 are you trying to protect some routes with the auth middleware? I use JWT for protected routes that returns JSON responses, it proved to be the easiest to implement and maintain. Simply return a token to the client once a user logs in, then submit authorization headers every time you send a request.

noleafclover614@gmail.com's avatar

At this point the only consumer of my API will be my application itself. I offer normal Laravel registration/login for users as well as Social authentication (Socialite). I looked into JWT for this but it seemed like overkill. Even if I did want to explore JWT for my scenario, I don't know where I'd store the token for users after they authenticate themselves.

mehany's avatar

You can use HTML5 localStorage which will give you access to the client side Storage Object.

That is the whole point of 5.2 MultiAuth drivers, it was designed to this kind of situations where you just want to use an Auth driver to authenticate some request the way you wish to authenticate it. Episode 39 on laravelPodcast, Taylor talks about this. but JWT Overkill, really ? For me it is the cherry on the top of a Orange cake.

noleafclover614@gmail.com's avatar

I did consider localStorage, but how do you store something on the client side without making another AJAX call after the user authenicates? For example, let's say the user authenticates normally (username /password or via a third party) and then the homepage loads. As far as I know the only way to then store data in localStorage is to do it via JavaScript. Where do I get the token from? Do I send it back in the HTTP headers after they authenticate the first time, then store it on the client? Something else?

Unless I am missing something, using JWT generally fits nicely if you are building an API that you plan on opening up to the public or third parties, where you need another way of authenticating and authorizing users before they interact with it. If you have an existing web application with a handful of RESTful API routes for your scattered JavaScript components (for example, Vue) to talk to, I don't know the best way to utilize the JWT flow.

mehany's avatar
Do I send it back in the HTTP headers after they authenticate the first time, then store it on the client?
yes, and it is pretty easy to implement. sample codebelow
 //in Angular 
$locationProvider.html5Mode(true);
$httpProvider.interceptors.push(['$rootScope', '$q', '$localStorage',
  function ($rootScope, $q, $localStorage) {

    return {
      request: function (config) {
        config.headers = config.headers || {};
        if ($localStorage.token) {
          config.headers.Authorization = 'Bearer ' + $localStorage.token;
        }
        return config;
      },
      response: function (res) {
        if (res.status === 401) {
          // Handle unauthenticated user.
        }
        return res || $q.when(res);
      }
    };
  }
]);

// in jQuery
var createRequestObject = [];//data
$.ajax({
        type:"POST",
        beforeSend: function (request)
        {
            request.setRequestHeader("Authority", authorizationToken);
        },
        url: "entities",
        data: "json=" + escape(JSON.stringify(createRequestObject)),
        success: function(msg) { }
});

and I think in Vue-resource will be something like this

Vue.http.interceptors.push({
    request: function (request) {
    request.headers.Authorization = 'Bearer ' + $localStorage.token;
            return request;
    },
    response: function (response) {
        return response;
   }
});

Middleware is nothing special, but when the user logs in you should create a token and keep refreshing the token lifetime throughout all requests or increase the lifetime of the token from the config settings.

     // example of handle method of a JWT auth middleware, or update existing auth driver.
          try {
        $user = JWTAuth::parseToken()->authenticate();
        Auth::setUser($user);
    }
    catch (TokenExpiredException $e) {

        return response()->json([
            'error' => 'Token Expired!',
            'statusCode' => (int)401
        ], 401);

    } catch (TokenInvalidException $e) {
        return response()->json([
            'error' => 'Not Authorized!',
            'statusCode' => (int)401
        ], 401);

    } catch (JWTException $e) {
        return response()->json([
            'error' => 'Not Authorized!',
            'statusCode' => (int)401
        ], 401);
    }

Route.php

Route::group(['prefix' => 'api/v1', 'before' => 'jwt.refresh', 'middleware' => 'jwt.auth'], function() {
     // JWT protected routes
})

Edit:

At login, below request and a response objects are injected

/**
 * Log a user in.
 *
 * @return Response
 */
public function login()
{
    $user = $this->user->authenticate(
        $this->req->input('username'), $this->req->input('password'));
    if (!$user) {
        return $this->res->json([
            'code' => null,
            'message' => 'Login failed',
            'description' => 'Wrong username/password.'

        ], Response::HTTP_UNPROCESSABLE_ENTITY);
    }
    $user['token'] = $this->jwtAuth->fromUser($user);
    return $this->res->json($user, Response::HTTP_OK);
}

Edit:

//login - note below, response and request objects are injected

/**
 * Log a user in.
 *
 * @return Response
 */
public function login()
{
    $user = $this->user->authenticate(
        $this->req->input('username'), $this->req->input('password'));
    if (!$user) {
        return $this->res->json([
            'code' => null,
            'message' => 'Login failed',
            'description' => 'Wrong username/password.'

        ], Response::HTTP_UNPROCESSABLE_ENTITY);
    }
    $user['token'] = $this->jwtAuth->fromUser($user);
    return $this->res->json($user, Response::HTTP_OK);
}
noleafclover614@gmail.com's avatar

Thank you for taking the time to reply with your examples. What if my Users are not logging in using AJAX requests and instead logging in via standard session based auth? In those cases I cannot send JSON back to them because I am routing them to my home page.

EDIT: I suppose I could just create or utilize some middleware that does the following when users request API routes... (does the jwt.auth middleware already do this?)

$user = Auth::user();  //since they are already authenticated in the session

$token = JWTAuth::fromUser($user);

$request['token'] = $token;

return $next($request);
noleafclover614@gmail.com's avatar

Maybe I am just misunderstanding the security architecture here. The multi auth capabilities sound cool, but the scenario described in that link simply assigns each user a 60 character token that, once obtained, grants access to your API as long as it's supplied in the request. Is this considered a secure method of authentication?

Please or to participate in this conversation.