Understanding the Rails Authenticity Token

前端 未结 10 1035
攒了一身酷
攒了一身酷 2020-11-22 05:55

I am running into some issues regarding the Authenticity Token in Rails, as I have many times now.

But I really don\'t want to just solve this problem and go on. I w

10条回答
  •  长情又很酷
    2020-11-22 06:25

    What is CSRF?

    The Authenticity Token is a countermeasure to Cross-Site Request Forgery (CSRF). What is CSRF, you ask?

    It's a way that an attacker can potentially hijack sessions without even knowing session tokens.

    Scenario:

    • Visit your bank's site, log in.
    • Then visit the attacker's site (e.g. sponsored ad from an untrusted organization).
    • Attacker's page includes form with same fields as the bank's "Transfer Funds" form.
    • Attacker knows your account info, and has pre-filled form fields to transfer money from your account to attacker's account.
    • Attacker's page includes Javascript that submits form to your bank.
    • When form gets submitted, browser includes your cookies for the bank site, including the session token.
    • Bank transfers money to attacker's account.
    • The form can be in an iframe that is invisible, so you never know the attack occurred.
    • This is called Cross-Site Request Forgery (CSRF).

    CSRF solution:

    • Server can mark forms that came from the server itself
    • Every form must contain an additional authentication token as a hidden field.
    • Token must be unpredictable (attacker can't guess it).
    • Server provides valid token in forms in its pages.
    • Server checks token when form posted, rejects forms without proper token.
    • Example token: session identifier encrypted with server secret key.
    • Rails automatically generates such tokens: see the authenticity_token input field in every form.

提交回复
热议问题