Angular CSRF Protection
Learn Angular CSRF protection with CSRF tokens, XSRF protection, SameSite cookies, HttpClient integration, secure authentication, enterprise architecture, OWASP best practices, and interview questions.
Cross-Site Request Forgery (CSRF), also known as Cross-Site Request Forgery (XSRF), is a web security attack that tricks an authenticated user into sending unintended requests to a trusted application.
If an application relies on browser cookies for authentication and does not implement CSRF protection, an attacker may be able to perform actions on behalf of the victim.
Angular provides built-in support for XSRF token handling through its HTTP client, but complete protection also requires secure backend implementation.
Table of Contents
- What is CSRF?
- How CSRF Works
- CSRF vs XSS
- Angular XSRF Protection
- CSRF Tokens
- SameSite Cookies
- Angular HttpClient Integration
- Backend Responsibilities
- Enterprise Banking Example
- Best Practices
- Common Mistakes
- Top 10 Interview Questions
- Interview Cheat Sheet
- Summary
What is CSRF?
A CSRF attack occurs when:
- A user logs into a trusted application.
- The browser stores the authentication cookie.
- The user visits a malicious website.
- The malicious site submits a forged request.
- The browser automatically includes the authentication cookie.
- The trusted server processes the request unless it validates a CSRF token or has equivalent protections.
CSRF Attack Flow
sequenceDiagram
participant User
participant Browser
participant Bank
participant MaliciousSite
User->>Bank: Login
Bank-->>Browser: Session Cookie
User->>MaliciousSite: Visit Website
MaliciousSite->>Browser: Hidden POST Request
Browser->>Bank: Sends Cookie Automatically
Bank-->>Browser: Request Processed (Without CSRF Protection)
Real-World Example
Imagine a user is logged into an online banking application.
A malicious webpage silently submits:
POST /transfer
amount=1000
account=987654
If the bank only relies on cookies for authentication and does not verify a CSRF token, the request could be processed as if the user intentionally submitted it.
Why Does CSRF Happen?
Browsers automatically send cookies for matching domains.
The browser cannot determine whether a request was initiated by:
- The legitimate application
- A malicious website
The server must verify that the request is legitimate.
Angular Security Architecture
flowchart LR
User
User --> AngularApp
AngularApp --> HttpClient
HttpClient --> XSRFToken
XSRFToken --> BackendAPI
BackendAPI --> Validation
Validation --> Database
CSRF vs XSS
| Feature | CSRF | XSS |
|---|---|---|
| Attack Type | Forged Request | Script Injection |
| Requires Login | Usually Yes | Not Always |
| Executes JavaScript | No | Yes |
| Uses User Session | Yes | Often |
| Primary Defense | CSRF Tokens | Sanitization + CSP |
What is a CSRF Token?
A CSRF token is a secure, unpredictable value generated by the server.
The server:
- Creates a unique token
- Sends it to the client
- Verifies it on state-changing requests
If the token is missing or invalid, the request is rejected.
CSRF Token Flow
sequenceDiagram
participant Browser
participant Angular
participant Server
Browser->>Server: Login
Server-->>Browser: Session Cookie + XSRF Cookie
Angular->>Browser: Read XSRF Cookie
Angular->>Server: POST Request + X-XSRF-TOKEN Header
Server->>Server: Validate Token
Server-->>Angular: Success
Angular Built-in XSRF Protection
Angular's HTTP client can automatically read an XSRF cookie and send its value in a request header.
Typical defaults are:
| Cookie Name | Header Name |
|---|---|
XSRF-TOKEN |
X-XSRF-TOKEN |
The backend validates the header value against the expected token.
Configuring Angular XSRF
Modern Angular applications can configure XSRF support when providing HttpClient.
bootstrapApplication(AppComponent, {
providers: [
provideHttpClient(
withXsrfConfiguration({
cookieName: 'XSRF-TOKEN',
headerName: 'X-XSRF-TOKEN'
})
)
]
});
Angular automatically includes the header for eligible same-origin mutating requests when the cookie is present.
Request Flow
flowchart LR
HttpClient
HttpClient --> ReadCookie
ReadCookie --> XSRFHeader
XSRFHeader --> Backend
Backend --> ValidateToken
ValidateToken --> Success
SameSite Cookies
Modern browsers support the SameSite cookie attribute.
Common values:
| Value | Description |
|---|---|
| Strict | Cookies are only sent for same-site requests |
| Lax | Cookies are sent for most same-site navigation and certain top-level cross-site navigations |
| None | Cookies are sent cross-site and must also include the Secure attribute |
Using appropriate SameSite settings significantly reduces many CSRF risks.
Secure Cookies
Authentication cookies should typically be configured with:
- Secure
- HttpOnly
- SameSite
Example
Set-Cookie:
SESSION=abc123;
Secure;
HttpOnly;
SameSite=Lax
The exact setting depends on your application's authentication flow.
Backend Responsibilities
Angular alone cannot prevent CSRF.
The backend should:
- Generate secure tokens
- Validate tokens
- Reject invalid requests
- Use HTTPS
- Configure secure cookies
- Apply proper authorization checks
Security is always a shared responsibility between client and server.
Enterprise Banking Example
A banking application processes:
- Money transfers
- Bill payments
- Credit card requests
- Loan applications
Security Flow
flowchart TD
Customer
Customer --> Login
Login --> SessionCookie
SessionCookie --> Angular
Angular --> XSRFHeader
XSRFHeader --> BankingAPI
BankingAPI --> TokenValidation
TokenValidation --> Transaction
Protection Layers
- HTTPS
- Session Cookie
- XSRF Token
- SameSite Cookies
- Authentication
- Authorization
- Audit Logging
Performance Considerations
| Practice | Benefit |
|---|---|
| Automatic XSRF Header | Less manual code |
| Cookie-based Token | Lightweight |
| SameSite Cookies | Browser protection |
| HTTPS | Secure transport |
| Backend Validation | Strong security |
Common Mistakes
Believing Angular Alone Prevents CSRF
Angular automatically sends the XSRF token only when properly configured.
The backend must still validate the token.
Disabling SameSite Cookies
Avoid disabling SameSite protection unless your application's cross-site requirements truly require it.
Ignoring HTTPS
Never transmit authentication cookies over plain HTTP in production.
Using GET for State Changes
State-changing operations should use appropriate HTTP methods such as:
- POST
- PUT
- PATCH
- DELETE
GET requests should remain safe and free of side effects.
Missing Server Validation
The backend must verify:
- Authentication
- Authorization
- CSRF token validity
Client-side checks alone are not sufficient.
Angular CSRF Best Practices
| Practice | Benefit |
|---|---|
| Enable XSRF Protection | Automatic token handling |
| Validate Tokens | Prevent forged requests |
| Use HTTPS | Secure communication |
| Configure SameSite Cookies | Browser-level defense |
| Use HttpOnly Cookies | Protect sensitive cookies |
| Validate on Server | Defense in depth |
| Use Proper HTTP Methods | RESTful security |
| Follow OWASP | Enterprise security |
Top 10 CSRF Interview Questions
1. What is CSRF?
Answer
CSRF (Cross-Site Request Forgery) is an attack that tricks an authenticated user's browser into sending unintended requests to a trusted application.
2. Why does CSRF occur?
Answer
Because browsers automatically include cookies with matching requests, a malicious website can potentially trigger authenticated requests unless additional protections are in place.
3. What is an XSRF token?
Answer
An XSRF token is a unique, server-generated value that the client returns with state-changing requests so the server can verify the request originated from the legitimate application.
4. How does Angular help prevent CSRF?
Answer
Angular's HTTP client can automatically read an XSRF cookie and include its value in a request header for eligible requests, making it easier to implement token-based CSRF protection.
5. Is Angular's XSRF support enough by itself?
Answer
No. The backend must generate, validate, and enforce the token. Without server-side validation, CSRF protection is incomplete.
6. What is the difference between CSRF and XSS?
Answer
CSRF forges authenticated requests, whereas XSS injects malicious scripts into web pages.
7. What are SameSite cookies?
Answer
SameSite cookies control when browsers send cookies during cross-site requests, helping reduce CSRF risks.
8. Why should applications use HTTPS?
Answer
HTTPS encrypts communication between clients and servers, protecting cookies, tokens, and other sensitive information during transit.
9. Should GET requests modify data?
Answer
No. GET requests should be safe and idempotent, while state-changing operations should use POST, PUT, PATCH, or DELETE.
10. What are Angular CSRF best practices?
Answer
- Enable Angular XSRF support
- Validate tokens on the server
- Use HTTPS
- Configure Secure, HttpOnly, and appropriate SameSite cookies
- Follow OWASP guidance
- Protect all state-changing endpoints
Interview Cheat Sheet
| Requirement | Recommended Solution |
|---|---|
| CSRF Protection | XSRF Tokens |
| Angular Support | HttpClient XSRF Configuration |
| Cookie Security | Secure + HttpOnly + SameSite |
| Transport Security | HTTPS |
| Token Validation | Backend |
| State-Changing Requests | POST/PUT/PATCH/DELETE |
| Session Security | Server Validation |
| Browser Protection | SameSite Cookies |
| Enterprise Security | OWASP |
| Production | Defense in Depth |
Summary
CSRF is a serious security vulnerability that targets authenticated users by exploiting automatically sent browser cookies. Angular simplifies client-side implementation by automatically including XSRF tokens in eligible HTTP requests, but complete protection requires secure backend validation, HTTPS, and properly configured cookies. Combining Angular's XSRF support with server-side defenses and OWASP best practices results in secure, enterprise-ready applications.
Key Takeaways
- ✅ CSRF targets authenticated browser sessions.
- ✅ Angular provides built-in support for XSRF token handling.
- ✅ Servers must generate and validate CSRF tokens.
- ✅ Use HTTPS for all authenticated communication.
- ✅ Configure Secure, HttpOnly, and appropriate SameSite cookies.
- ✅ Never rely solely on client-side protection.
- ✅ Use proper HTTP methods for state-changing operations.
- ✅ Backend authorization remains essential.
- ✅ Follow OWASP recommendations for defense in depth.
- ✅ CSRF protection is a common Angular and web security interview topic.
Next Article
➡️ 106-Authentication-vs-Authorization-QA.md