I'm working on Laravel 5.4 and my routes are in the api middleware
I see that I need to transfer my routes to the web middleware, but I need them to be on the api middleware since I'm creating a RESTful api, any suggestions on how I could use csrf with api middleware?
Laravel CSRF Token Ajax Calls In Laravel, Middleware handles all the requests and doesn't allow any POST request without the right CSRF token verification. Therefore, in order to proceed further, you must input the CSRF Token while sending the AJAX request.
Enable CSRF Protection With REST API If our project requires CSRF protection, we can send the CSRF token with a cookie by using CookieCsrfTokenRepository in a custom WebSecurityConfigurerAdapter. After restarting the app, our requests receive HTTP errors, which means that CSRF protection is enabled.
Enabling cross-site request forgery (CSRF) protection is recommended when using REST APIs with cookies for authentication. If your REST API uses the WCToken or WCTrustedToken tokens for authentication, then additional CSRF protection is not required.
csrf_field(): This function can be used to generate the hidden input field in the HTML form. Note: This function should be written inside double curly braces. csrf_token(): This function just gives a random string. This function does not generate the hidden input field.
CSRF protection prevents attacks using a previously authenticated user (normally setting a state using session) https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF).
A restful API do not have state https://en.wikipedia.org/wiki/Representational_state_transfer, so there is no session to attack. So in a restful API the CSRF protection is to authenticate the user on each request, if you are only authenticating the user on the first request and use session for the following requests you are not making a restfull API and should use the web middleware.
Edit: How are you going to get the CSRF token to the client if you don't have any state?
you can use any middleware as well as your custom middleware in any route group. Laravel makes it very easy for us. Just open the Kernel.php
file in App\Http
namespace. Find protected $middlewareGroups
probable on line 28 and the change the code like below to allow the enable Csrf
protection in api routes:
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
'throttle:60,1',
'bindings',
\App\Http\Middleware\VerifyCsrfToken::class,
],
];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With