leafsphp / leaf

🍁 The easiest way to create clean, simple but powerful web apps and APIs quickly
https://leafphp.dev
MIT License
1.07k stars 64 forks source link

Authenticating API routes in leaf framework #176

Closed kofesto closed 1 year ago

kofesto commented 1 year ago

The Leaf framework documentation does not include authenticating API, my question is how do I authenticate API routes or the framework doesn't include that ? And also there is no error handling mechanism, I guess that could be customized by the programmer leveraging on the container on the framework or using middleware, but my major concern is the API route authentication. Thanks to the team for this wonderful framework, just discovered it this year and I really want to explore it and possibly use it for production apps

mychidarko commented 1 year ago

Hi @kofesto, thanks for the compliments. By authenticating API, do you mean having an auth flow eg: JWTs with Bearer tokens?

iammiloslukic commented 1 year ago

@kofesto The best way to do is to create a Auth middleware and to call it for all routes. This way you can create an authentication that you need (API-KEY, Bearer, etc.)

This is how I do it:

app()->before('GET', '/.*', function () { }, ['middleware' => ['ApiAuthentication']]);

kofesto commented 1 year ago

Hi @kofesto, thanks for the compliments. By authenticating API, do you mean having an auth flow eg: JWTs with Bearer tokens?

Yes I mean authentication flow all API routes with JWT token, the documentation for middleware is not comprehensive enough, I know the auth flow can be handled by creating an authentication middleware

kofesto commented 1 year ago

@kofesto The best way to do is to create a Auth middleware and to call it for all routes. This way you can create an authentication that you need (API-KEY, Bearer, etc.)

This is how I do it:

app()->before('GET', '/.*', function () { }, ['middleware' => ['ApiAuthentication']]);

I get your explanation, but then the problem is how do I create an authentication middleware ?

iammiloslukic commented 1 year ago

@kofesto

Create ApiAuthentication.php to middleware folder.

To class you need to create yourself depends on what your needs are, but the start is like this:

class ApiAuthentication extends Leaf\Middleware{ }

And that's it. The code I sent earlier should be located in _app.php

iammiloslukic commented 1 year ago

@kofesto If you struggle with the Class try using ChatGPT or search the web for some code

kofesto commented 1 year ago

To class you need to create yourself depends on what your needs are, but the start is like this:

class ApiAuthentication extends Leaf\Middleware{ }

Thanks I get it now