Home >Backend Development >PHP Tutorial >Laravel middleware: used to prevent cross-site request forgery (CSRF) attacks

Laravel middleware: used to prevent cross-site request forgery (CSRF) attacks

WBOY
WBOYOriginal
2023-07-30 16:27:29855browse

Laravel middleware: used to prevent cross-site request forgery (CSRF) attacks

Overview:
In Internet applications, cross-site request forgery (CSRF) attacks are a common network security threat . CSRF attacks forge malicious requests to allow users to perform illegal operations without their knowledge, such as changing passwords, transferring funds, etc. To prevent this kind of attack, Laravel provides a built-in middleware that can easily protect applications from CSRF attacks.

Usage of CSRF middleware:
In Laravel, using CSRF middleware is very simple. First, we need to register the middleware in the application's routing file. Open the app/Http/Kernel.php file, find the web middleware group, and add the VerifyCsrfToken middleware as follows:

protected $middlewareGroups = [
    'web' => [
        // 其他中间件...
        AppHttpMiddlewareVerifyCsrfToken::class,
    ],
    // 其他中间件组...
];

When the middleware is registered, Laravel will automatically generate a token for each request and store it in the session. Each time a POST, PUT, or DELETE request is sent, Laravel will compare the token in the request with the token stored in the session. If they are inconsistent, the request will be rejected and an error will be returned.

Generate CSRF token:
Laravel provides a global csrf_token helper function for generating a CSRF token in the view. In an HTML form, we can protect the form from CSRF attacks by adding a hidden input field in the ff9c23ada1bcecdd1a0fb5d5a0f18437 tag and setting the value of the input field to the CSRF token.

<form method="POST" action="/submit">
    @csrf
    <!-- 其他表单字段... -->
    <button type="submit">提交</button>
</form>

In the above example, we used the @csrf directive to generate a hidden CSRF token input field. This instruction will automatically insert a hidden d5fd7aea971a85678ba271703566ebfd tag in the generated HTML, with the name _token and the value being CSRF token.

If you use Laravel's built-in form helper function (such as Form::open), you do not need to manually add the CSRF token input field, Laravel will automatically generate it for you.

Manually verify CSRF token:
In addition to automatic verification, Laravel also provides a method to manually verify CSRF token so that we can complete more fine-grained verification in the controller or routing callback. We can use the csrf_token auxiliary function to obtain the CSRF token of the current request, and obtain the token stored in the session by calling the session method of the Request object.

The following is an example of manually verifying the CSRF token in the controller:

<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;
use IlluminateSupportFacadesSession;

class UserController extends Controller
{
    public function updateProfile(Request $request)
    {
        $token = $request->input('_token');
        if (!hash_equals(Session::token(), $token)) {
            // CSRF token验证失败
            abort(403, 'Unauthorized action.');
        }

        // CSRF token验证通过,继续处理操作
        // ...
    }
}

In the above example, we used the hash_equals function to compare the token in the request Whether it is consistent with the token in the session to ensure the security of CSRF token verification.

Summary:
Laravel's CSRF middleware provides a simple yet powerful way to prevent cross-site request forgery attacks. By automatically generating and validating CSRF tokens, we can effectively protect our applications from malicious requests. Whether it is automatic verification or manual verification, Laravel provides us with flexible and reliable options to secure our applications.

The above is the detailed content of Laravel middleware: used to prevent cross-site request forgery (CSRF) attacks. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn