Synchronizer token pattern example

Hello devs, hope all you are doing well. Here an example of the synchronizer token pattern that uses for Cross-Site Request Forgery (CSRF).

Before the code, Just have an idea about the workflow of the Synchronizer token pattern. Have a look in below diagram.

Synchronizer token pattern workflow

First, I have designed and developed a Login page for the demonstration purpose.

Landing page

For the demo purpose, I have hardcoded the email address and the password and not validated the email also.

Let’s start with the front end interface implementation. It’s basically a simple form that the method is post and the action is /login.

In the Sign in button, simply capture the values from the above input fields and submit it to the action.

In here, I have implemented onPageLoad method to get the csrf token from the server. On the page load, this method gets invoked and set a hidden input filed for the form also.

function onPageLoad() {fetch('/validate', {credentials: 'same-origin',method: 'POST',body: {},headers: {'Content-Type': 'application/json'}}).then((resp) => resp.json()).then(function (data) {console.log(JSON.stringify(data));var form = document.getElementById("form");var input = document.createElement("input");input.type = "hidden";input.name = "_csrf";input.value = data.csrfToken;form.appendChild(input);})}

Let’s move to the backend server script. I have implemented an expressJs server for this demo.

When the serve starting point, server is returning the index.html page which i mentioned in above.

app.get('/', (req, res) => {res.sendFile(path.join(__dirname, 'index.html'));})

Once the onPageLoad method is called from the index page, the server script will return the csrf token from the validation routing.

app.post('/validate', parseForm, function (req, res) {console.log(req)var token = req.session.csrfToken;console.log('validate().token : ' + token);res.json({ csrfToken: token });})

Afterwards, the server will wait for any request from the frontend. Once the frontend calls the login action by submitting the form along with the csrf token that issued before, Login route will then check that request csrf token with the in-memory token. And if both tokens are matching, response will return with the home.html. Otherwise it returns the 403 unauthorized status.

When the tokens are matched

Git Repository can be find in here

Thank you. See you again.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade