How do you implement CSRF protection in Angular applications? (original) (raw)
Last updated on Aug 29, 2024
Powered by AI and the LinkedIn community
CSRF, or cross-site request forgery, is a type of web attack that exploits the trust between a user and a server. It occurs when a malicious website or script sends a request to a server on behalf of a user, without their consent or knowledge. For example, a hacker could trick a user into clicking a link that transfers money from their bank account to the hacker's account, using the user's authentication cookies.
To prevent CSRF attacks, web applications need to implement some form of protection mechanism that verifies the origin and integrity of the requests. One common method is to use a CSRF token, which is a random and unique value that is generated by the server and attached to each request. The server then checks if the token matches the one stored in the session or cookie, and rejects any request that does not have a valid token.
Angular is a popular framework for building web applications that use TypeScript, HTML, and CSS. Angular has built-in support for CSRF protection, which works as follows:
Top experts in this article
Selected by the community from 8 contributions. Learn more
Make sure the server validates the CSRF token while on incoming request. Use the HttpXsrTokenExtractor service. Work on server-side CSRF protection Add it the CSRF token in Angular's HTTP headers using an interceptor.
Angular uses HTTP cookies to store the CSRF token and send it with each request. To enable this feature, you need to import the HttpClientModule from @angular/common/http and add it to the imports array of your AppModule. This will automatically configure the HttpClient service to use the XSRFStrategy interface, which handles the cookie and header names for the token.
To set up CSRF protection in an Angular app, first, ensure your server generates a CSRF token, sets it as a cookie (XSRF-TOKEN), and validates it on requests. In Angular, import HttpClientModule in your AppModule to handle CSRF tokens automatically. HttpClient will use the XSRF-TOKEN cookie to include the CSRF token in the X-XSRF-TOKEN header for requests. If needed, you can customize this behavior, but the default setup is usually sufficient. Verify that the token is correctly set in cookies and included in request headers, and ensure your server is properly validating it.
Ensure your backend sets the XSRF-TOKEN cookie with the appropriate value during authentication or login. If you're using a different library or custom logic for CSRF protection, the process might differ. For detailed guidance, refer to the official Angular documentation: [[invalid URL removed]]([invalid URL removed])
If you wish to use a different cookie and header name, HttpClientXsrfModule has a method called withOptions. The usage looks like this: imports: [ HttpClientModule, HttpClientXsrfModule.withOptions({ cookieName: 'your-custom-Xsrf-Cookie', headerName: 'your-custom-Xsrf-Header' }) ] HttpClientXsrfModule implements its default HttpXsrfInterceptor as its interceptor. An interceptor is a service that transforms an outgoing HTTP request. You can also disable the CSRF protection using HttpClientXsrfModule.disable().
To set up CSRF protection in your Angular app, you need to match Angular's expectations with your server's conventions. By default, Angular looks for a CSRF token in a cookie named XSRF-TOKEN and sends it back in a header named X-XSRF-TOKEN. If your server uses different names, you can customize this. First, create a custom service to extract the CSRF token from the cookie and another service if you need to handle tokens differently. Then, override the default Angular services in your AppModule to use your custom ones. This way, Angular will fetch and send the CSRF token according to your server's setup, ensuring secure communication between your app and backend.
Backend service must be configured to set the cookie for your page, and to verify that the header is present on all eligible requests. When performing HTTP requests, the HttpClient interceptor reads a token from a cookie, by default XSRF-TOKEN, and sets it as an HTTP header, X-XSRF-TOKEN, although customising these defaults is also possible with the help of HttpClientXsrfModule.withOptions(). Because only code that runs on your domain could read the cookie, the backend can be certain that the HTTP request came from your client application and not an attacker.
Send requests with HttpClient
To send requests with the CSRF token, you need to use the HttpClient service, which is injected as a dependency in your components or services. The HttpClient service automatically reads the token from the cookie and adds it to the header of each request, as long as the request is sent to the same domain as the application. You can use the various methods of the HttpClient service, such as get, post, put, or delete, to send requests with different HTTP verbs and options.
- To protect your Angular app from CSRF attacks, you first need your backend to generate and validate CSRF tokens. When a user accesses your app, the server should send a CSRF token as a cookie. Angular’s HttpClient service handles tokens automatically if the app and server are on the same domain. Just make sure to include cookies with requests by setting withCredentials to true in your HttpClient calls. If you need to manually handle tokens, you can extract them from cookies and include them in request headers. Additionally, configure your cookies with the SameSite and Secure attributes to enhance security. Lastly, test your setup thoroughly to ensure the CSRF protection is working as expected.
More relevant reading
``