-1

As far as I understood, I need protection against csrf attacks when I use jwt by storing them in http-only cookies.

So that when a user visits a malicious site and a request to my server is made from there with jwt cookies automatically enabled, I can protect the user from unwanted actions.

And for this, you need to use a csrf token.

But it is also stored in cookies, and there is a chance that an attacker will try to get it through an xss attack. Or if it's also http-only, it will be automatically sent by the browser just like jwt cookies.

So, what's the point of using a csrf token? Please help me understand, thanks!

3

1 Answer 1

0

When storing JWTs in HttpOnly cookies, you're protecting the token from JavaScript-based XSS (Cross-Site Scripting) attacks, as these cookies cannot be accessed or manipulated by client-side scripts. However, this alone does not prevent CSRF (Cross-Site Request Forgery) attacks, where a malicious website might automatically include the JWT cookie in a request to your server, potentially leading to unwanted actions.

To defend against CSRF attacks, you need to implement a CSRF token. The CSRF token is usually stored in a non-HttpOnly cookie or as part of the HTML response. This token is then manually sent with requests, often in a custom HTTP header (e.g., X-CSRF-Token). When a request is made, the server validates that the CSRF token matches what was set for that session. Since an attacker’s site won’t have access to this token, they cannot forge legitimate requests.

In this way, the HttpOnly cookie protects the JWT from XSS, while the CSRF token ensures requests are coming from legitimate sources, offering comprehensive protection.

For further reading on the topic, consider reviewing the following resource:

  1. https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html

  2. JWT and CSRF differences

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.