Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use access_token to authenticate SPA with Laravel 5.4

I'm trying to authenticate my single page app (written in Marionette) with my Laravel 5.4 app. In my previous experience, an SPA would:

  • send the username & password to an /api/login-token endpoint which would return with something like the following:

    { "access_token":"-wt7x8UPRH9GcbTeUQ3wIA7zuc02XeHil4qsoKJcOUU", "type":"Bearer", "expires_in":2570, "refresh_token":"g9zmNkC1zpQ8fM0uSeJdy_VZe7TuBUG4MYGIBuAtXvg" }

  • the SPA will store the access_token in the browser's localstorage, and send it in an access_token header with every subsequent request made to the backend

  • the backend will recognise this access_token and authenticate the user

Unfortunately I'm struggling to understand how to achieve this in Laravel 5.4.

Do I need to use Passport? I really don't think I need OAuth2, but does Passport also offer simple token-based auth? It seems to, and I have gotten the expected tokens described above from the /oauth/token endpoint, but I don't know how to use this token. I don't think it's even for this purpose.

I tried sending a request to /api/user with this token in the headers, POSTing it, and as a query string, with no luck. Also making me concerned is the expires_in from Laravel is a year (31536000 seconds = 365 days) which seems way too long. I'm worried this Passport OAuth token is actually for OAuth2 access and not a 1-day-ish expiring access token that I'm used to.

I also read about Laravel's TokenGuard but that seems like some weird kind of token that's stored in an api_token column on the user table, which is all wrong by my mindset. For example, it doesn't expire, and it's per-user not per-user-session, meaning the same token would have to be used from multiple devices. etc

Very confused... grateful for any help!

like image 468
jeff-h Avatar asked Dec 20 '25 11:12

jeff-h


1 Answers

You may try JWT and this tutorial might be an inspiration for you: https://scotch.io/tutorials/token-based-authentication-for-angularjs-and-laravel-apps

like image 61
Oluwatobi Samuel Omisakin Avatar answered Dec 23 '25 17:12

Oluwatobi Samuel Omisakin