CSRF & Nonce

CSRF

Introduction

  • Cross-Site Request Forgery (CSRF) is an attack that forces an end user to execute unwanted actions on a web application in which they’re currently authenticated. With a little help of social engineering (such as sending a link via email or chat), an attacker may trick the users of a web application into executing actions of the attacker’s choosing. If the victim is a normal user, a successful CSRF attack can force the user to perform state changing requests like transferring funds, changing their email address

Example

<form action="https://small-min.blog.com/delete" method="POST">
  <input type="hidden" name="id" value="3"/>
  <input type="submit" value="開始測驗"/>
</form>

Prevention

  • Required same site cookies for the specific api for every request for authentication

  • Generate CSRF Token from the server, and pass it to front-end, make sure every non-get route request must contain CSRF token

Nonce

Introduction

  • Nonce (Number Used Once) stands for a random that only be used once only

  • To make sure the uniqueness of every request to prevent from duplicate execution of the request

Example

  • Client

<form method="POST" action="/submit-order">
  <input type="hidden" name="nonce" value="123456789abcdef">
  <input type="text" name="orderDetails">
  <button type="submit">提交訂單</button>
</form>
  • Server

if (isNonceValid(request.body.nonce)) {
    processOrder();
    invalidateNonce(request.body.nonce);
} else {
    throw new Error("Invalid nonce!");
}

Difference

  • Nonce is to make sure the uniqueness of each request

  • CSTF is to validate the correctness of the request

Reference

Last updated

Was this helpful?