> For the complete documentation index, see [llms.txt](https://petercheng7788.gitbook.io/developer-note/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://petercheng7788.gitbook.io/developer-note/frontend/web-security/csrf-and-nonce.md).

# CSRF & Nonce

## CSRF

### Introduction

<figure><img src="https://1374779285-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MFW3x2aqEO8GF2kr3VU%2Fuploads%2F5xhTDkGANrBtzyqiCQhd%2Fimage.png?alt=media&amp;token=36173d92-3a25-4998-874d-72d483e7057e" alt=""><figcaption></figcaption></figure>

* 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

```html
<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

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

* Server

```javascript
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

{% embed url="<https://www.thingsaboutweb.dev/zh-TW/posts/nonce-and-csrf-token>" %}

{% embed url="<https://owasp.org/www-community/attacks/csrf>" %}

{% embed url="<https://blog.techbridge.cc/2017/02/25/csrf-introduction/>'" %}
