Git Product home page Git Product logo

strapi-jwt-cookies's Introduction

Strapi JWT Cookies

Securely use users-permissions's JWT on cookies. Compatible with Strapi v4 and requires @strapi/plugin-users-permissions@^4.1.12

@bwyx/strapi-jwt-cookies on npm

How this package works

This package extends the @strapi/plugin-users-permissions core plugin via Extending a plugin's interface. It exports a higher-order function to wrap strapi-server customization.

What this package does to the plugin

Features

  • Split JWT into two cookies, httpOnly for JWT header.signature and javascript-accessible cookie for the payload, so frontend can easily read the JWT payload. read it more here
  • Automatically log out on user inactivity by setting cookie expires

How About CSRF?

Note that this package doesn't add a CSRF prevention mechanism, but it does ensure the request is from the frontend by using SameSite flag sets to lax, and by checking request custom headers which only can be sent from the same CORS domain.

  • set X-Requested-With to XMLHttpRequest to be able receive and validate jwt cookies on the server

Install

npm install --save @bwyx/strapi-jwt-cookies

Create file under directory src/extensions/users-permissions/strapi-server.js:

// src/extensions/users-permissions/strapi-server.js

module.exports = require('@bwyx/strapi-jwt-cookies')(); 

If you already extend the strapi-server.js, you could wrap your function like this:

const withJwtCookie = require('@bwyx/strapi-jwt-cookies');

module.exports = withJwtCookie((plugin) => {
  // some customization

  return plugin
});

Then add the global middleware, this middleware reconstructs JWT from request cookies and then assigns it to headers.authorization

// config/middlewares.js

module.exports = [
  'strapi::errors',
  ...
  'strapi::public',
  'plugin::users-permissions.jwtCookieGetter'
]

Configurations

By default, frontend users will be logged out after 30 mins of inactivy (not make an api request)

COOKIE_PAYLOAD_LIFESPAN_MINUTES=30

You can restrict the cookie to your specific frontend domain (recommended):

FRONTEND_DOMAIN=myfrontend.com

The default cookies name are user for the payload and token for headers.signature, you can prefix the cookies name with env

APP_NAME=myapp

then the cookies will be myapp_user and myapp_token

TODO

  • Add test (?)

References

strapi-jwt-cookies's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

strapi-jwt-cookies's Issues

Add option to secure graphql route

Is there a way to apply the cookie setting/getting to the graphql route as well?

We're using Apollo Client on the frontend and the graphql plugin. When I send a login mutation using the graphql, there are no cookies set, but they're set when I send the request to the /api/auth/local endpoint.

to readme

add Strapi version compatibility in readme (v3. or v4)

Persistent login?

Hey, thank you for your work! Cookie based login definitely improves this whole process.

I have a question: I do see, that you increase the lifetime of the session cookie every time a request comes through (except for the logout endpoint), but wouldn't that still mean, that the jwt token would be invalid at some point? I think the default is 30 days and since this will not be renewed, would it mean, that the user would be forcefully logged out after 30 days at the latest, even if they do constant requests?

Is this by design or was there just no easy solution? Would be really interested in that. Thank you in advance for answering!

Allow for postman/api tools to get cookie

I really like this plugin, it should be officially supported.

That said, I noticed the check in the setter should allow for api tools to check login. I initially thought the plugin didn't work, but realized it only works when the request passes the isFromFrontend() check. Happy to do a PR to allow for this if you have suggestions.

    if (
      isFromFrontend(request) &&
      response.status === 200 &&
      response.body.jwt
    ) 

Strapi 4.15 compatibility

Trying to use this plugin in a TypeScript project with Strapi 4.15.2, getting this error when running strapi ts:generate-types:

Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: Package subpath './server/routes/content-api/auth' is not defined by "exports" in /app/node_modules/@strapi/plugin-users-permissions/package.json
    at new NodeError (node:internal/errors:399:5)
    at exportsNotFound (node:internal/modules/esm/resolve:361:10)
    at packageExportsResolve (node:internal/modules/esm/resolve:697:9)
    at resolveExports (node:internal/modules/cjs/loader:567:36)
    at Module._findPath (node:internal/modules/cjs/loader:636:31)
    at Module._resolveFilename (node:internal/modules/cjs/loader:1063:27)
    at Module._load (node:internal/modules/cjs/loader:922:27)
    at Module.require (node:internal/modules/cjs/loader:1143:19)
    at require (node:internal/modules/cjs/helpers:110:18)
    at Object.<anonymous> (/app/node_modules/@bwyx/strapi-jwt-cookies/index.js:3:20) {
  code: 'ERR_PACKAGE_PATH_NOT_EXPORTED'
}

With Strapi 4.14.6, everything works fine.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.