ParserDoer
ParserDoer

Reputation: 85

Laravel API Project - Design and Authentication

I am tasked with building an external API for customers. Without giving any business data away, the database consists of our entire workflow. Events generated, associated tickets and other information, all distinguishable by customer.

I want to build an api with very simple endpoints. For each table, say tickets for example, I wish to have two endpoints:

/tickets            #will return a list of tickets and general information
/ticket/<ticket_id> #More detailed information about the specific ticket

For any customer that authenticates, these routes will only return those DB records for which they are associated.

I have not written a system like this in Laravel before. Am I correct in understanding that Passport is the way to go? I guess I am asking if there are simpler ways to do authentication of this type securely (is Passport overkill)? If we have a small set of customers, and are fine with setting up their authentication for them, would certificates be a better way to go? Or is OAuth2 such the industry standard now that not using Passport is a mistake?

If Passport is best, is it better to have the OAuth2 server and application server be separate sites, or can they be combined into one app?

Thanks for any advice.

Upvotes: 3

Views: 553

Answers (1)

EddyTheDove
EddyTheDove

Reputation: 13259

Although passport is recommended, you can still use simple API authentication by giving your user an api_token attribute. If you set that token in the request headers, Laravel will automaticall authenticate the user. Though you have to use the auth:api middleware.

If you use auth:api middleware, you can do in your controller $user = Auth::guard('api')->user(); and it will automatically return the user sending the request.

This post nicely explains what to do: https://gistlog.co/JacobBennett/090369fbab0b31130b51. It gives the following steps:

  1. Add api_token to the user migration as string
  2. Define a grouped route with middleware in routes/api.php

    Route::group(['middleware' => 'auth:api', 'prefix' => 'v1'], function() { Route::resource('tickets', 'TicketController'); });

And you are good to go.

The Route::resource() with handle both /tickets and /tickets/123 as long as you define public function index() and public function show() in your controller.

URL to the api call will look like http://website.com/api/v1 as I prefixed the group with v1.

Upvotes: 4

Related Questions