Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 8: Using Fortify in APIs

Can Laravel Fortify be used in the context of API? From what I understand, Fortify (although being headless, i.e. doesn't include a UI layer) allows us to customize Login and Register pages, but it automatically redirects to HOME page upon successful authentication. And although the HOME page is customizable, that is not how API logins normally work. It should simply return a success token in JSON format without redirects of any kind.

There is an authenticateUsing function in Fortify, but even that simply allows us to customize authentication logic and not the returned data. Redirection is still performed by Fortify.

How can I use Fortify in the context of REST API?

Note: I'm going to use it from my Vue front-end application. I'm also going to get Sanctum into the game, but before that I just wanted to see if I can do regular token-based authentication using Fortify without having to write my own login, register and logout routes and controller functions.

like image 558
dotNET Avatar asked Sep 24 '20 04:09

dotNET


2 Answers

Authentication can either be Session-based or Token-based.

Laravel Fortify only provides the backend logic nessecery for session-based authentication and therefore is not intended for token-based API authentication.

If you need token-based API authentication, you can use either Sanctum or Passport depending on your needs. But You'll have to write a bit of code, in either case.

If you decide to go with Laravel Passport, I have a boilerplate project that might be of use: https://github.com/pktharindu/laravel-api-boilerplate-passport

like image 99
P. K. Tharindu Avatar answered Oct 24 '22 09:10

P. K. Tharindu


Just set 'Accept' header with 'application/json' or 'application/javascript' then fortify will response json formatted body not redirection.

by the way, use Sanctum instead of Passport for SPA is easier to keep token securely. google about where to store API token for SPA then you will find out why.

like image 12
pejold Avatar answered Oct 24 '22 10:10

pejold