Cross-Site Request Forgery (CSRF) is a type of attack where a malicious actor tricks a user into performing actions on a website or application without the user’s knowledge or consent. This is possible because the attacker takes advantage of the fact that browsers automatically send cookies, including session cookies, along with every HTTP request. CSRF attacks often target users who are authenticated to perform unauthorized actions, such as changing account settings or transferring funds.
In AngularJS applications, mitigating the risk of CSRF attacks involves implementing proper security measures to ensure that malicious actors cannot manipulate users’ data by submitting unauthorized requests.
Steps to Prevent CSRF Attacks in AngularJS
- Use Same-Site Cookies
- The SameSite cookie attribute allows you to control when cookies should be sent with cross-origin requests. By setting
SameSite
toStrict
orLax
, you can prevent the browser from sending cookies with cross-origin requests, significantly reducing the chances of CSRF attacks.
- Strict: Cookies are sent only if the request originates from the same origin as the target.
- Lax: Cookies are sent with same-origin requests and top-level navigations, but not with cross-origin requests.
angular.module('app').config(function($cookiesProvider) { $cookiesProvider.defaults.sameSite = 'Strict'; // or 'Lax' based on your use case });
- The SameSite cookie attribute allows you to control when cookies should be sent with cross-origin requests. By setting
- Use Anti-CSRF Tokens The most effective way to prevent CSRF attacks is to use anti-CSRF tokens. These tokens are unique to each session and are sent with every HTTP request. The server verifies the token to ensure the request is legitimate. AngularJS supports adding custom headers to HTTP requests. You can use an anti-CSRF token to verify the authenticity of requests and prevent unauthorized actions. Steps for Using Anti-CSRF Tokens:
- Generate a Token on the Server: The server generates a unique token for each user session and sends it to the client. This can be done during login or when a user session is initialized.
- Send the Token with Requests: On the client-side (in AngularJS), add the token as a custom header with each request. Example using
$http
service: javascriptCopyEditangular.module('app').config(function($httpProvider) { $httpProvider.defaults.headers.common['X-CSRF-Token'] = 'your-csrf-token-here'; });
- Verify the Token on the Server: On the server, every request that modifies state (e.g., POST, PUT, DELETE requests) should verify the CSRF token in the request headers against the token stored on the server.
- Server-side Example (Node.js with Express):
app.use(csrf()); // Middleware to check for CSRF token app.post('/updateProfile', function(req, res) { // Ensure CSRF token matches if (req.csrfToken() !== req.headers['x-csrf-token']) { return res.status(403).send('Invalid CSRF token'); } // Process the update });
- Configure $httpProvider for Automatic CSRF Protection AngularJS has a built-in mechanism to add the CSRF token automatically with the
$httpProvider
service. This ensures that every HTTP request made by AngularJS carries the CSRF token. Example: You can configure the$httpProvider
to attach the CSRF token to all outgoing requests by setting theX-XSRF-TOKEN
header to the value of the CSRF token stored in the browser cookies.angular.module('app').config(function($httpProvider) { // Enable XSRF protection $httpProvider.defaults.xsrfCookieName = 'XSRF-TOKEN'; $httpProvider.defaults.xsrfHeaderName = 'X-XSRF-TOKEN'; });
This code automatically attaches the CSRF token to all outgoing requests if the cookieXSRF-TOKEN
is set. - Enable HTTPS (SSL/TLS) CSRF attacks can be facilitated by man-in-the-middle (MITM) attacks, especially when sensitive data is transmitted over HTTP. Enabling HTTPS ensures that communication between the client and server is encrypted, preventing malicious parties from intercepting and modifying requests.
- Force HTTPS: Ensure that your application is only accessible over HTTPS and redirect all HTTP traffic to HTTPS.
if (process.env.NODE_ENV === 'production') { app.use((req, res, next) => { if (req.protocol === 'http') { return res.redirect(301, `https://${req.headers.host}${req.url}`); } next(); }); }
- Limit Cookie Usage and Set Secure Flags Cookies are often a target in CSRF attacks. To enhance cookie security, always use the
Secure
,HttpOnly
, andSameSite
flags:- Secure: Cookies will only be sent over HTTPS connections.
- HttpOnly: Prevents JavaScript from accessing the cookie, protecting against XSS attacks.
- SameSite: Restricts cross-origin cookie sending to mitigate CSRF.
angular.module('app').config(function($cookiesProvider) { $cookiesProvider.defaults.secure = true; // Ensure cookies are only sent over HTTPS $cookiesProvider.defaults.httpOnly = true; // Prevent JavaScript access to cookies $cookiesProvider.defaults.sameSite = 'Strict'; // Or 'Lax' });
- Use RESTful Design with HTTP Methods One way to reduce CSRF risks is to use the appropriate HTTP methods for different actions:
- GET: Should be used for fetching data only. It should not modify any state.
- POST: Used for submitting data or triggering actions.
- PUT: Used for updating resources.
- DELETE: Used for deleting resources.
- Implement Content Security Policy (CSP) Implementing a strong Content Security Policy (CSP) helps mitigate the risk of malicious scripts running in the context of your website. By restricting the sources of executable scripts, CSP makes it harder for attackers to inject and execute malicious JavaScript that could steal cookies or perform CSRF attacks. Example CSP header:
Content-Security-Policy: default-src 'self'; script-src 'self'; style-src 'self'; object-src 'none';
This policy restricts scripts and other resources to only be loaded from the same origin as the website, significantly reducing the attack surface.