All Projects → fastify → fastify-csrf

fastify / fastify-csrf

Licence: other
A fastify csrf plugin.

Programming Languages

javascript
184084 projects - #8 most used programming language
typescript
32286 projects

Projects that are alternatives of or similar to fastify-csrf

fastify-postgres
Fastify PostgreSQL connection plugin
Stars: ✭ 144 (+63.64%)
Mutual labels:  fastify, fastify-plugin
fastify-vite
This plugin lets you load a Vite client application and set it up for Server-Side Rendering (SSR) with Fastify.
Stars: ✭ 497 (+464.77%)
Mutual labels:  fastify, fastify-plugin
spring-security-jwt-csrf
A demonstration of stateless JWT authentication with Spring Security, Spring Boot and Vue js
Stars: ✭ 62 (-29.55%)
Mutual labels:  csrf, csrf-protection
fastify-loader
The route loader for the cool kids!
Stars: ✭ 17 (-80.68%)
Mutual labels:  fastify, fastify-plugin
fastify-env
Fastify plugin to check environment variables
Stars: ✭ 129 (+46.59%)
Mutual labels:  fastify, fastify-plugin
www-project-csrfguard
The aim of this project is to protect Java applications against CSRF attacks with the use of Synchronizer Tokens
Stars: ✭ 43 (-51.14%)
Mutual labels:  csrf, csrf-protection
fastify-caching
A Fastify plugin to facilitate working with cache headers
Stars: ✭ 123 (+39.77%)
Mutual labels:  fastify, fastify-plugin
fastify-cors
Fastify CORS
Stars: ✭ 212 (+140.91%)
Mutual labels:  fastify, fastify-plugin
fastify-axios
Add axios http client to your fastify instance
Stars: ✭ 28 (-68.18%)
Mutual labels:  fastify, fastify-plugin
fastify-autoroutes
fastest way to map directories to URLs in fastify
Stars: ✭ 70 (-20.45%)
Mutual labels:  fastify, fastify-plugin
fastify-awilix
Dependency injection support for fastify
Stars: ✭ 52 (-40.91%)
Mutual labels:  fastify, fastify-plugin
fastify-accepts
Add accepts parser to fastify
Stars: ✭ 51 (-42.05%)
Mutual labels:  fastify, fastify-plugin
okta-spring-boot-react-crud-example
Simple CRUD with React and Spring Boot 2.0
Stars: ✭ 214 (+143.18%)
Mutual labels:  csrf, csrf-protection
fastify-vue
A nuxt.js fastify plugin
Stars: ✭ 27 (-69.32%)
Mutual labels:  fastify, fastify-plugin
fastify-openapi-glue
A plugin for Fastify to autogenerate a configuration based on a OpenApi(v2/v3) specification.
Stars: ✭ 94 (+6.82%)
Mutual labels:  fastify, fastify-plugin
csrf-login
Login from command line to the websites that use CSRF protection
Stars: ✭ 18 (-79.55%)
Mutual labels:  csrf, csrf-protection
fastify-etag
Automatically generate etags for HTTP responses, for Fastify
Stars: ✭ 61 (-30.68%)
Mutual labels:  fastify, fastify-plugin
fastify-passport
Use passport strategies for authentication within a fastify application
Stars: ✭ 150 (+70.45%)
Mutual labels:  fastify, fastify-plugin
fastify-file-upload
Fastify plugin for uploading files
Stars: ✭ 68 (-22.73%)
Mutual labels:  fastify, fastify-plugin
fastify-cron
Run cron jobs alongside your Fastify server 👷
Stars: ✭ 32 (-63.64%)
Mutual labels:  fastify, fastify-plugin

@fastify/csrf-protection

CI NPM version js-standard-style

This plugin helps developers protect their Fastify server against CSRF attacks. In order to fully protect against CSRF, developers should study Cross-Site Request Forgery Prevention Cheat Sheet in depth. See also pillarjs/understanding-csrf as a good guide.

Security Disclaimer

Securing applications against CSRF is a developer responsibility and it should not be fully trusted to any third party modules. We do not claim that this module is able to protect an application without a clear study of CSRF, its impact and the needed mitigations. @fastify/csrf-protection provides a series of utilities that developers can use to secure their application. We recommend using @fastify/helmet to implement some of those mitigations.

Security is always a tradeoff between risk mitigation, functionality, performance, and developer experience. As a result we will not consider a report of a plugin default configuration option as security vulnerability that might be unsafe in certain scenarios as long as this module provides a way to provide full mitigation through configuration.

Install

npm i @fastify/csrf-protection

Usage

Use with @fastify/cookie

If you use @fastify/csrf-protection with @fastify/cookie, the CSRF secret will be added to the response cookies. By default, the cookie used will be named _csrf, but you can rename it via the cookieKey option. When cookieOpts are provided, they override the default cookie options. Make sure you restore any of the default options which provide sensible and secure defaults.

fastify.register(require('@fastify/cookie'))
fastify.register(require('@fastify/csrf-protection'))

// if you want to sign cookies:
fastify.register(require('@fastify/cookie'), { secret }) // See following section to ensure security
fastify.register(require('@fastify/csrf-protection'), { cookieOpts: { signed: true } })

// generate a token
fastify.route({
  method: 'GET',
  path: '/',
  handler: async (req, reply) => {
    const token = await reply.generateCsrf()
    return { token }
  }
})

// protect a route
fastify.route({
  method: 'POST',
  path: '/',
  onRequest: fastify.csrfProtection,
  handler: async (req, reply) => {
    return req.body
  }
})

Use with @fastify/session

If you use @fastify/csrf-protection with @fastify/session, the CSRF secret will be added to the session. By default, the key used will be named _csrf, but you can rename it via the sessionKey option.

fastify.register(require('@fastify-session'))
fastify.register(require('@fastify/csrf-protection'), { sessionPlugin: '@fastify/session' })

// generate a token
fastify.route({
  method: 'GET',
  path: '/',
  handler: async (req, reply) => {
    const token = await reply.generateCsrf()
    return { token }
  }
})

// protect a route
fastify.route({
  method: 'POST',
  path: '/',
  onRequest: fastify.csrfProtection,
  handler: async (req, reply) => {
    return req.body
  }
})

Use with @fastify/secure-session

If you use @fastify/csrf-protection with @fastify/secure-session, the CSRF secret will be added to the session. By default, the key used will be named _csrf, but you can rename it via the sessionKey option.

fastify.register(require('@fastify/secure-session'))
fastify.register(require('@fastify/csrf-protection'), { sessionPlugin: '@fastify/secure-session' })

// generate a token
fastify.route({
  method: 'GET',
  path: '/',
  handler: async (req, reply) => {
    const token = await reply.generateCsrf()
    return { token }
  }
})

// protect a route
fastify.route({
  method: 'POST',
  path: '/',
  onRequest: fastify.csrfProtection,
  handler: async (req, reply) => {
    return req.body
  }
})

Securing the secret

The secret shown in the code above is strictly just an example. In all cases, you would need to make sure that the secret is:

  • Never hard-coded in the code or .env files or anywhere in the repository
  • Stored in some external services like KMS, Vault or something similar
  • Read at run-time and supplied to this option
  • Of significant character length to provide adequate entropy
  • Truly random sequence of characters (You could use crypto-random-string)

Apart from these safeguards, it is extremely important to use HTTPS for your website/app to avoid a bunch of other potential security issues like MITM attacks etc.

API

Module Options

Options Description
cookieKey The name of the cookie where the CSRF secret will be stored, default _csrf.
cookieOpts The cookie serialization options. See @fastify/cookie.
sessionKey The key where to store the CSRF secret in the session.
getToken A sync function to get the CSRF secret from the request.
getUserInfo A sync function to get the a string of user-specific information to prevent cookie tossing.
sessionPlugin The session plugin that you are using (if applicable).
csrfOpts The csrf options. See @fastify/csrf.

reply.generateCsrf([opts])

Generates a secret (if it is not already present) and returns a promise that resolves to the associated secret.

const token = await reply.generateCsrf()

You can also pass the cookie serialization options to the function.

The option userInfo is required if getUserInfo has been specified in the module option. The provided userInfo is hashed inside the csrf token and it is not directly exposed. This option is needed to protect against cookie tossing.

fastify.csrfProtection(request, reply, next)

A hook that you can use for protecting routes or entire plugins from CSRF attacks. Generally, we recommend using an onRequest hook, but if you are sending the token via the request body, then you must use a preValidation or preHandler hook.

// protect the fastify instance
fastify.addHook('onRequest', fastify.csrfProtection)

// protect a single route
fastify.route({
  method: 'POST',
  path: '/',
  onRequest: fastify.csrfProtection,
  handler: async (req, reply) => {
    return req.body
  }
})

You can configure the function to read the CSRF token via the getToken option, by default the following is used:

function getToken (req) {
  return (req.body && req.body._csrf) ||
    req.headers['csrf-token'] ||
    req.headers['xsrf-token'] ||
    req.headers['x-csrf-token'] ||
    req.headers['x-xsrf-token']
}

It is recommended to provide a custom getToken function for performance and security reasons.

fastify.register(require('@fastify/csrf-protection'), { getToken: function (req) { req.headers['csrf'] } })

License

MIT

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].