Angular + Laravel API authentication/authorization best practice
Hi guys,
for educational purposes I'm relaunching an existing website. Backend stays laravel 7, the frontend will be developed with Angular 11 instead of classic blades (html/css/jquery). The new site will be hosted on another server and domain.
I'm still evaluating but there might be an issue with CORS/authentication/authorization against my API.
Requests (GET) from my frontend should be the only ones getting answers from my API and the POST are only accepted coming from frontend.
Thus I need some sort of authentication/authorization system.
For noncritical public information like getting the dynamic pagetitle (received from database/api) a simple CORS-allowance should be fine, right?
In general, is there a best practice for CRUD-operations when backend (Laravel) and frontend (Angular) are on different domains? Are there alternatives to OAuth2/JWT and how to I prevend csrf exploits?
Okay, so let me try to unpack that a little. You have an API that only serves publicly available information, correct? If so, it's correct that you can set a CORS header to prevent other websites querying your API within a browser. However, one can of course still query your API with a script or something like curl.
If your API also serves private, protected information you should already have an authentication and authorization system in place. If so, are you using Laravel's built-in session-based authentiation?
To prevent CSRF attacks, you should continue to use Laravel's CSRF middleware protection. Since your frontend is separately served, of course its HTML cannot contain a CSRF token. To work around that, you should send an XHR GET request to your backend to fetch the token before submitting any state-alerting requests with alternative HTTP methods.