javck
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    --- tags: laravel --- # CSRF保護 ![](https://i.imgur.com/1d7U3VF.jpg) ## 簡介 跨站請求偽造是一種惡意攻擊,它憑藉已通過身份驗證的用戶身份來行使未經過其授權的命令,而Laravel 可以輕鬆地保護應用程序免受這種跨站請求偽造(CSRF)攻擊 Laravel 會自動為每個活躍的用戶的會話生成一個 CSRF「口令」。該口令用於驗證經過身份驗證的用戶是否是向應用程序發出請求的用戶。 無論何時,當在應用中定義 HTML 表單時,都應該在表單中包含一個隱藏的 CSRF 標記字串,以便 CSRF 保護中介層可以驗證該請求,你可以使用 @csrf 這個 Blade 標籤來生成口令字串 ### 漏洞說明 假如你不太了解跨站請求偽造(CSRF),讓我舉個例子來說明到底這個漏洞可以怎麼被利用。想像一下你的應用有個 /user/email 路由接受一個 POST 請求來變更驗證使用者的email。極可能的是,這個路由會包含一個email輸入項用來提供使用者需要使用的email 如果沒有 CSRF 保護,某個偽造網站就能夠建立一個 HTML 表單指向你的 /user/email 路由並提供駭客希望你拿到的email,一旦得逞之後,後面將會是一連串的慘劇發生 ``` <form action="https://your-application.com/user/email" method="POST"> <input type="email" value="malicious-email@example.com"> </form> <script> document.forms[0].submit(); </script> ``` 假如該偽造網站寫成是當頁面被載入時就自動提交這個表單,那麼駭客只需要吸引應用的用戶去訪問偽造網站,他們的email就會被你的應用給修改,成了未察覺的受害人 為了防堵這個漏洞,我們需要去檢查每個進入的POST, PUT, PATCH, or DELETE 請求是否帶有一個機密的口令,而這個口令偽造網站是得不到的 ## 防止 CSRF 請求 Laravel會自動為被應用管理的活躍用戶對話去建立一個 CSRF "口令(token)"。這個口令用來確認這個驗證用戶是否真的是使用應用的表單來發出請求。因為這個口令是存在用戶的 session 裡頭,而且會隨著每一次 session 重新生成而改變,偽造網站是得不到的 當前 session 的 CSRF 口令可以透過 request 的 session 又或者是幫助函式 csrf_token()來取得 ``` use Illuminate\Http\Request; Route::get('/token', function (Request $request) { $token = $request->session()->token(); $token = csrf_token(); // ... }); ``` 每當你在應用裡頭定義一個 HTML 表單,你都需要加入一個隱藏的 CSRF 輸入項,名為 _token ,值就是要傳送的口令內容。而 CSRF 防護中介層就能夠驗證這個請求是否來自應用 為了簡便,你也可以使用 @csrf 這個Blade標籤來生成這個隱藏輸入項: ``` <form method="POST" action="/profile"> @csrf <!-- Equivalent to... --> <input type="hidden" name="_token" value="{{ csrf_token() }}" /> </form> ``` 預設被定義在 web 中介層群組的 App\Http\Middleware\VerifyCsrfToken 中介層,將會自動的驗證請求中的token是否符合存在 session 當中的token。如果符合的話,我們就知道這個請求真的是用戶自己發出的 ### CSRF Tokens & SPAs 假如你正打造一個 SPA 應用而選擇 Laravel 作為API後端,你應該研究一下 [Laravel Sanctum 文件](https://laravel.com/docs/8.x/sanctum)來取得更多有關API的驗證以及防範 CSRF 攻擊的資訊 >所謂SPA指的是 Single Page Application,也就是頁面不需要重載就能夠更新畫面,就如同原生應用一樣 ### 排除 URIs 不受 CSRF保護 有時你會想要讓一些 URIs 能夠免於 CSRF 防護。比如你正使用 Stripe 來進行付款並實作它們的 webhook 系統,你就會需要將你的 Stripe webhook 處理器路由從 CSRF 防護中排除,因為 Stripe 是不會知道 CSRF token 的,也就不可能將之傳回給你 一般來說,你應該把這類型的路由移出由 App\Providers\RouteServiceProvider 分配給 web 中介層群組的 routes/web.php。然而,你也可以透過把這些要排除的 URIs 加入 VerifyCsrfToken 中介層的 $except 屬性當中 ``` <?php namespace App\Http\Middleware; use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware; class VerifyCsrfToken extends Middleware { /** * The URIs that should be excluded from CSRF verification. * * @var array */ protected $except = [ 'stripe/*', 'http://example.com/foo/bar', 'http://example.com/foo/*', ]; } ``` > 為了方便,當進行測試時 CSRF 中介層會自動的被關閉,不對所有路由進行防護 ## X-CSRF-Token 除了檢查 POST 參數中的 CSRF 口令之外, VerifyCsrfToken 中介層還會檢查 X-CSRF-TOKEN Header。你應該將口令保存在 HTML meta 標籤當中,如下例: `<meta name="csrf-token" content="{{ csrf_token() }}">` 接著一旦你創建了 meta 標籤,就可以指示像 jQuery 這樣的函式庫自動將口令添加到所有請求的Header當中。這為基於 AJAX 的應用提供簡單,方便的 CSRF 保護。如下: ``` $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }); ``` ## X-XSRF-Token Laravel 將當前的 CSRF 口令保存在一個 XSRF-TOKEN cookie 中,該 cookie 包含在框架生成的每個回應當中。你可以使用 cookie 值來設置 X-XSRF-TOKEN Header 這個 cookie 主要是作為一種方便使用者的方式發送的,因為一些 JavaScript 框架和函式庫,例如 Angular 和 Axios ,會自動將它的值放入 X-XSRF-TOKEN Header 裡頭 技巧:預設情況下,resources/js/bootstrap.js 文件包含的 Axios HTTP 函式庫,會自動為你發送 CSRF 口令 Header。

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully