国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

目錄
What does @csrf do in Laravel?
When and where to use @csrf
How to handle CSRF tokens with JavaScript/AJAX
Things to watch out for
首頁 php框架 Laravel 如何使用@CSRF Blade指令來防止CSRF攻擊?

如何使用@CSRF Blade指令來防止CSRF攻擊?

Jun 18, 2025 am 12:23 AM
csrf保護 Blade指令

@csrf在Laravel中用於防止CSRF攻擊,其通過在表單中自動生成一個包含安全令牌的隱藏字段實現(xiàn)保護。當用戶提交表單時,服務器會驗證該令牌,若不匹配則拒絕請求,從而阻止惡意站點偽造請求。你應在所有執(zhí)行狀態(tài)更改操作的表單中使用@csrf,例如登錄、註冊、評論提交及修改數(shù)據(jù)庫數(shù)據(jù)的表單,即使某些表單看似“安全”也應啟用保護。對於使用AJAX或前端框架的情況,可通過讀取XSRF-TOKEN cookie(如Axios自動處理)或手動從meta標籤獲取令牌並在請求頭中添加X-CSRF-TOKEN來發(fā)送令牌。另外需要注意:不要無故禁用CSRF保護,API亦應採用Sanctum或Passport等機制;長期存在的頁面應定期刷新令牌;SPA應用建議結合Laravel Sanctum確保安全??傊?,在表單中加入@csrf或在請求中攜帶令牌可有效防禦大多數(shù)CSRF攻擊,雖簡單但易被忽略。

Laravel's @csrf Blade directive is one of the easiest and most effective ways to protect your forms from CSRF (Cross-Site Request Forgery) attacks. Here's how it works and how you should use it.


What does @csrf do in Laravel?

When you include @csrf inside a form in a Blade template, Laravel automatically generates a hidden input field containing a CSRF token. This token is a secure, randomly generated value that the server checks when the form is submitted. If the token doesn't match what Laravel expects, the request gets rejected — preventing malicious third-party sites from submitting requests on behalf of a logged-in user.

You'll typically see it used like this:

 <form method="POST" action="/submit">
    @csrf
    <!-- other form fields -->
</form>

Behind the scenes, Laravel turns that into something like:

 <input type="hidden" name="_token" value="randomly-generated-token-value">

This token is required for any POST, PUT, PATCH, or DELETE request handled by Laravel's routes that are protected by the VerifyCsrfToken middleware (which they are by default).


When and where to use @csrf

You should always use @csrf in forms that perform state-changing actions — especially when users are logged in. Here are some common scenarios:

  • User login forms
  • Registration forms
  • Comment submission forms
  • Any form that modifies data in the database

?? Important : Don't skip @csrf just because a form seems "safe". Even search forms or newsletter signups can be abused if not protected properly.

If you're using Vue, React, or another frontend framework that sends AJAX requests instead of traditional form submissions, you'll need to handle the CSRF token differently — more on that below.


How to handle CSRF tokens with JavaScript/AJAX

When you're not submitting forms the traditional way (like with Axios or Fetch API), you still need to send the CSRF token. Laravel makes this easy by setting a cookie called XSRF-TOKEN by default. Many HTTP clients (like Axios) will read this cookie automatically and set the X-XSRF-TOKEN header for you.

If you're manually managing headers, here's how you can get the token from the cookie and include it in your requests:

  1. Get the token from the cookie:

     function getCookie(name) {
        let matches = document.cookie.match(new RegExp(
            "(?:^|; )" name.replace(/([\.$?*|{}\(\)\[\]\\\/\ ^])/g, &#39;\\$1&#39;) "=([^;]*)"
        ));
        return matches ? decodeURIComponent(matches[1]) : undefined;
    }
    
    const token = getCookie(&#39;XSRF-TOKEN&#39;);
  2. Send it with your request:

     fetch(&#39;/your-endpoint&#39;, {
        method: &#39;POST&#39;,
        headers: {
            &#39;Content-Type&#39;: &#39;application/json&#39;,
            &#39;X-CSRF-TOKEN&#39;: token
        },
        body: JSON.stringify({ /* your data */ })
    });

Alternatively, you can embed the token directly in your Blade view:

 <meta name="csrf-token" content="{{ csrf_token() }}">

Then grab it from there in your JS code.


Things to watch out for

  • Never disable CSRF protection without a good reason – even APIs used by mobile apps should use some kind of token-based authentication (like Sanctum or Passport).
  • CSRF tokens expire after a while , so if you have long-lived pages with forms, consider refreshing the token periodically.
  • If you're building a SPA and using Laravel as an API backend, look into Laravel Sanctum for managing CSRF and session authentication securely.

基本上就這些。只要在表單裡加上@csrf ,或者在前端請求裡帶上token,就能擋住大多數(shù)CSRF 攻擊。不復雜但容易忽略。

以上是如何使用@CSRF Blade指令來防止CSRF攻擊?的詳細內(nèi)容。更多資訊請關注PHP中文網(wǎng)其他相關文章!

本網(wǎng)站聲明
本文內(nèi)容由網(wǎng)友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發(fā)現(xiàn)涉嫌抄襲或侵權的內(nèi)容,請聯(lián)絡admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅(qū)動的應用程序,用於創(chuàng)建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發(fā)環(huán)境

Dreamweaver CS6

Dreamweaver CS6

視覺化網(wǎng)頁開發(fā)工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

Laravel的政策是什麼,如何使用? Laravel的政策是什麼,如何使用? Jun 21, 2025 am 12:21 AM

InLaravel,policiesorganizeauthorizationlogicformodelactions.1.Policiesareclasseswithmethodslikeview,create,update,anddeletethatreturntrueorfalsebasedonuserpermissions.2.Toregisterapolicy,mapthemodeltoitspolicyinthe$policiesarrayofAuthServiceProvider.

如何在操作系統(tǒng)(Windows,MacOS,Linux)上安裝Laravel? 如何在操作系統(tǒng)(Windows,MacOS,Linux)上安裝Laravel? Jun 19, 2025 am 12:31 AM

是的,YouCaninStallaLaveRonanyOperatingSystembyFollowingTheSeSteps:1.InstallphpandRequiredExtensionsLikeMbString,OpenSSL,AndxmlusingtoolslikeXampponwindows,HomebrewhonMacos,HomebrewonMacos,homebbrewonmacos,homebtonlinux,oraptonlinux;

Laravel中的控制器是什麼,他們的目的是什麼? Laravel中的控制器是什麼,他們的目的是什麼? Jun 20, 2025 am 12:31 AM

控制器在Laravel中的主要作用是處理HTTP請求並返迴響應,以保持代碼的整潔和可維護性。通過將相關請求邏輯集中到一個類中,控制器使路由文件更簡潔,例如將用戶資料展示、編輯和刪除等操作分別放在UserController的不同方法中。創(chuàng)建控制器可通過Artisan命令phpartisanmake:controllerUserController實現(xiàn),而資源控制器則使用--resource選項生成,涵蓋標準CRUD操作的方法。接著需在路由中綁定控制器,如Route::get('/user/{id

如何自定義Laravel中的身份驗證視圖和邏輯? 如何自定義Laravel中的身份驗證視圖和邏輯? Jun 22, 2025 am 01:01 AM

Laravel允許通過覆蓋默認存根和控制器來自定義認證視圖和邏輯。 1.要自定義認證視圖,可使用命令phpartisanvendor:publish--tag=laravel-auth將默認Blade模板複製到resources/views/auth目錄並進行修改,例如添加“服務條款”複選框。 2.要修改認證邏輯,需調(diào)整RegisterController、LoginController和ResetPasswordController中的方法,如更新validator()方法以驗證新增字段,或重寫r

如何使用Laravel的驗證系統(tǒng)來驗證形式數(shù)據(jù)? 如何使用Laravel的驗證系統(tǒng)來驗證形式數(shù)據(jù)? Jun 22, 2025 pm 04:09 PM

Laravelprovidesrobusttoolsforvalidatingformdata.1.Basicvalidationcanbedoneusingthevalidate()methodincontrollers,ensuringfieldsmeetcriterialikerequired,maxlength,oruniquevalues.2.Forcomplexscenarios,formrequestsencapsulatevalidationlogicintodedicatedc

選擇特定的列|性能優(yōu)化 選擇特定的列|性能優(yōu)化 Jun 27, 2025 pm 05:46 PM

1.FetchingAllColumnSIncreaseSemory,網(wǎng)絡和ProPersingSingoverHead.2.unnectaryDatareTrievalPreventSefefectivefectivefective.2.nynynyneedcolumnsimprovesperformenceByReDucingReSouranceByReDucingRessourceUsage.1.fetchingallcolumnsincreasemory

如何使用{{{{...}}}在刀片模板中逃脫HTML輸出? (注意:很少使用,更喜歡{{...}}) 如何使用{{{{...}}}在刀片模板中逃脫HTML輸出? (注意:很少使用,更喜歡{{...}}) Jun 23, 2025 pm 07:29 PM

inlaravelBladeTemplates,使用{{{...}}} todisplayrawhtml.bladeescapescontentwithin {{...}} fullhtmlspecialchars() ks.但是,三重橋式播放,呈現(xiàn),呈現(xiàn)thtmlas-is.thisshouldbodedspareSpareDandanlylythlylythlylythlusteddata.Acceptablecase

我如何在Laravel測試中模擬依賴項? 我如何在Laravel測試中模擬依賴項? Jun 22, 2025 am 12:42 AM

tomockDepentencies forcectiesInallaravel,distrypentenceptionforservices,syseReceive()forfacades,andmockeryforcomplexcases.1.forinjectedServices,使用$ this-> instance()tore-> instance()

See all articles