0
0
PHPprogramming~15 mins

CSRF attacks and token protection in PHP - Deep Dive

Choose your learning style9 modes available
Overview - CSRF attacks and token protection
What is it?
CSRF stands for Cross-Site Request Forgery. It is a type of attack where a bad website tricks your browser into doing something on another website without your permission. Token protection is a way to stop these attacks by using secret codes called tokens that only your website knows. These tokens make sure that requests come from real users, not attackers.
Why it matters
Without protection against CSRF, attackers can make users unknowingly change their settings, send money, or do harmful actions on websites they are logged into. This can cause loss of money, data leaks, or damage to trust. Token protection helps keep users and websites safe by making sure actions are genuine.
Where it fits
Before learning about CSRF and tokens, you should understand how web forms and sessions work in PHP. After this, you can learn about other web security topics like XSS (Cross-Site Scripting) and authentication best practices.
Mental Model
Core Idea
CSRF attacks trick your browser into sending unwanted requests, and token protection stops this by verifying a secret code unique to each user session.
Think of it like...
Imagine you have a special stamp that only you and your trusted friend know. Every time your friend sends you a letter, they put this stamp on it. If a letter arrives without the stamp, you know it’s fake and ignore it.
┌───────────────┐       ┌───────────────┐
│ User's Browser│──────▶│ Target Website│
│               │       │               │
│ Sends Request │       │ Checks Token  │
└───────────────┘       └───────────────┘
          │                      ▲
          │                      │
          │                      │
          └─────Token Missing────┘

If token is missing or wrong, request is rejected.
Build-Up - 7 Steps
1
FoundationUnderstanding CSRF Basics
🤔
Concept: What CSRF attacks are and how they exploit trust in browsers.
CSRF attacks happen when your browser is tricked into sending a request to a website where you are logged in. For example, if you are logged into your bank, a bad website can make your browser send a money transfer request without you knowing.
Result
Attackers can perform actions on your behalf without your consent.
Understanding that browsers automatically send cookies with requests explains why CSRF attacks can happen without user interaction.
2
FoundationHow Sessions and Cookies Work
🤔
Concept: Sessions keep track of logged-in users using cookies sent automatically by browsers.
When you log into a website, it creates a session and stores your login info on the server. Your browser keeps a cookie with a session ID and sends it with every request. This lets the website know who you are.
Result
Your browser sends cookies automatically, which attackers can exploit in CSRF.
Knowing that cookies are sent automatically helps explain why extra checks are needed to stop CSRF.
3
IntermediateIntroducing CSRF Tokens
🤔
Concept: Tokens are secret codes added to forms to verify requests come from the real user.
A CSRF token is a random string generated by the server and stored in the user's session. It is added as a hidden field in forms. When the form is submitted, the server checks if the token matches the one in the session.
Result
Only requests with the correct token are accepted, blocking forged requests.
Tokens create a secret handshake between the user and server that attackers cannot guess.
4
IntermediateImplementing Token Generation in PHP
🤔
Concept: How to create and store a CSRF token in PHP sessions.
This code creates a secure random token and saves it in the session.
Result
A unique token is ready to be added to forms for protection.
Using secure random bytes ensures tokens are hard to guess, increasing security.
5
IntermediateValidating Tokens on Form Submission
🤔
Concept: Checking the token sent by the user matches the session token to allow the request.
This code stops the request if the token is missing or wrong.
Result
Only valid requests with correct tokens proceed.
Validating tokens prevents attackers from forging requests even if cookies are sent.
6
AdvancedHandling Token Expiry and Regeneration
🤔Before reading on: Should CSRF tokens stay the same forever or change over time? Commit to your answer.
Concept: Tokens should be refreshed periodically to reduce risk if leaked.
Tokens can be regenerated after successful form submission or after a time limit. This limits the window attackers have to reuse tokens. For example, after processing a form, generate a new token:
Result
Tokens stay fresh and harder to reuse by attackers.
Refreshing tokens reduces risk from token theft or reuse in long sessions.
7
ExpertToken Protection Limits and Double Submit Cookies
🤔Quick: Does sending the same CSRF token in a cookie and form field always prevent CSRF? Commit to yes or no.
Concept: Alternative methods like double submit cookies exist but have tradeoffs.
Double submit cookies send the CSRF token both as a cookie and a form value. The server checks if both match. This avoids server-side session storage but can be weaker if attackers can read cookies via XSS. Token protection is best combined with other security measures.
Result
Understanding alternative methods helps choose the right protection for your app.
Knowing the limits of token methods prevents overconfidence and encourages layered security.
Under the Hood
When a user loads a form, the server generates a random token and stores it in the session. This token is embedded in the form as a hidden field. When the form is submitted, the server compares the submitted token with the session token. If they match, the request is accepted; otherwise, it is rejected. This works because attackers cannot read the user's session or token, so they cannot forge valid requests.
Why designed this way?
CSRF tokens were designed to solve the problem that browsers automatically send cookies with requests, making it easy for attackers to trick users. By adding a secret token that only the real user and server know, the server can verify requests are genuine. Alternatives like checking Referer headers were unreliable, so tokens became the standard.
┌───────────────┐       ┌───────────────┐       ┌───────────────┐
│ Server       │       │ User's Browser│       │ Attacker Site │
│ Generates    │       │ Loads Form    │       │ Tries to Send │
│ Token        │──────▶│ with Token    │       │ Fake Request  │
│ Stores Token │       │               │       │               │
└───────────────┘       └───────────────┘       └───────────────┘
          │                      │                      │
          │                      │                      │
          │                      │                      │
          │                      │                      │
          │                      │                      │
          │                      │                      │
          │                      │                      │
          ▼                      ▼                      ▼
┌───────────────────────────────────────────────────────────┐
│ Server receives request and checks if token matches session│
│ If yes, process request; if no, reject as CSRF attempt     │
└───────────────────────────────────────────────────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does having a login session alone stop CSRF attacks? Commit to yes or no.
Common Belief:If a user is logged in, the website is safe from CSRF because the session cookie is secret.
Tap to reveal reality
Reality:CSRF attacks exploit the fact that browsers send session cookies automatically, so being logged in does not stop CSRF.
Why it matters:Assuming login alone protects leads to vulnerable sites where attackers can perform actions without user consent.
Quick: Is it safe to use a fixed CSRF token for all users and sessions? Commit to yes or no.
Common Belief:Using the same CSRF token for all users is fine because it’s secret and hard to guess.
Tap to reveal reality
Reality:Tokens must be unique per user session; a fixed token can be guessed or reused by attackers.
Why it matters:Using fixed tokens allows attackers to bypass protection and perform CSRF attacks.
Quick: Does checking the Referer header reliably prevent CSRF? Commit to yes or no.
Common Belief:Checking the Referer header is enough to stop CSRF attacks.
Tap to reveal reality
Reality:Referer headers can be missing or spoofed, so relying on them alone is unreliable.
Why it matters:Relying on Referer checks can give a false sense of security and leave sites vulnerable.
Quick: Can double submit cookie method fully replace server-side token storage? Commit to yes or no.
Common Belief:Double submit cookies are always as secure as server-stored tokens.
Tap to reveal reality
Reality:Double submit cookies can be weaker if attackers exploit XSS to read cookies.
Why it matters:Misunderstanding this can lead to weaker security in applications relying solely on double submit cookies.
Expert Zone
1
CSRF tokens should be unpredictable and tied to user sessions to prevent token reuse across users.
2
Token validation must be done on every state-changing request, including AJAX calls, not just form submissions.
3
Combining CSRF tokens with SameSite cookie attributes strengthens protection by limiting cookie sending.
When NOT to use
Token protection is less effective if your site is vulnerable to XSS attacks, as attackers can steal tokens. In such cases, fixing XSS is a priority. Also, for APIs using stateless authentication like JWT, other methods like custom headers or OAuth scopes are better alternatives.
Production Patterns
In real-world PHP apps, CSRF tokens are generated per session and embedded in all forms and AJAX requests. Frameworks often provide helpers to automate this. Tokens are rotated after successful submissions. Combined with secure cookie flags and Content Security Policy, this forms a layered defense.
Connections
XSS (Cross-Site Scripting)
Complementary security concepts
Understanding CSRF helps highlight why preventing XSS is critical, since XSS can steal CSRF tokens and bypass protection.
Authentication and Sessions
Builds on session management
Knowing how sessions and cookies work is essential to grasp why CSRF attacks happen and how tokens protect them.
Bank Check Verification
Similar verification pattern
Just like banks verify signatures on checks to prevent fraud, CSRF tokens verify requests to prevent forgery.
Common Pitfalls
#1Not adding CSRF tokens to all forms and state-changing requests.
Wrong approach:
Correct approach:
Root cause:Forgetting to include tokens leaves forms vulnerable to CSRF attacks.
#2Not validating the CSRF token on the server side.
Wrong approach:
Correct approach:
Root cause:Assuming token presence in form is enough without server verification.
#3Reusing the same CSRF token forever without regeneration.
Wrong approach:
Correct approach:
Root cause:Not refreshing tokens increases risk if tokens are leaked or guessed.
Key Takeaways
CSRF attacks trick browsers into sending unwanted requests by exploiting automatic cookie sending.
CSRF tokens are secret codes unique to each user session that verify requests are genuine.
Tokens must be generated securely, added to all forms, and validated on the server side.
Refreshing tokens regularly reduces risk from token theft or reuse.
Token protection is a critical layer of web security but must be combined with other measures like XSS prevention.