Git Product home page Git Product logo

nexus-plugin-jwt-auth's Introduction

header

Contents

Installation

npm install nexus-plugin-jwt-auth

Example Usage

Find full examples using both the built in permissions system or by leveragering nexus-plugin-shield:

Setup

// app.ts

import { use } from 'nexus'
import { auth } from 'nexus-plugin-jwt-auth'

// Enables the JWT Auth plugin without permissions
use(auth({
  appSecret: "<YOUR SECRET>" // optional if using custom verify function
}))

You may now access the token object and it's properties on the Nexus context.

Permissions

Basic permissions can be added too.

// app.ts

import { use } from 'nexus'
import { auth } from 'nexus-plugin-jwt-auth'

// Define the paths you'd like to protect
const protectedPaths = [
    'Query.me',
    'Query.filterPosts',
    'Query.post',
    'Mutation.createDraft',
    'Mutation.deletePost',
    'Mutation.publish'
]

// Enables the JWT Auth plugin with permissions
use(auth({
  appSecret: "<YOUR SECRET>", // optional if using custom verify function
  protectedPaths // optional
}))

Stored Properties

You can also access properties stored in the token.

In this example I sign the token on signup or login then store the userId in the token to be accessed directly in a query or mutation to find the authed user.

// Query.ts

import { schema } from 'nexus'

schema.queryType({
  definition(t) {
    t.field('me', {
      type: 'User',
      async resolve(_root, _args, ctx) {
        const user = await ctx.db.user.findOne({
          where: {
            id: ctx.token.userId // This is the token object passed through the context
          }
        })

        if (!user) {
          throw new Error('No such user exists')
        }

        return user
      }
    })
  }
})

Use cookie instead of Authorization header

import { use, server } from "nexus"
import cookieParser from "cookie-parser" // Set esModuleInterop: true in tsconfig.json

// Add the cookie-parser middleware to Express
server.express.use(cookieParser())

// Enables the JWT Auth plugin with cookies
use(auth({
  // ...
  useCookie: true,
  cookieName: "token"
}))

Don't forget to set credentials: true in your GraphQL client or the cookie will not be sent to the server.

Contributing

Please read CONTRIBUTING.md

License

FOSSA Status

nexus-plugin-jwt-auth's People

Contributors

azsiaz avatar camji55 avatar dependabot[bot] avatar homerjam avatar houfio avatar jonestristand avatar wassafr avatar zeko369 avatar

Stargazers

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

Watchers

 avatar  avatar  avatar

nexus-plugin-jwt-auth's Issues

Cannot use GraphQLSchema "[object GraphQLSchema]" from another module or realm.

Hello!

I'm using the version 0.23.0-next.10 of nexus in a yarn workspace and after having installed the plugin I had the following error

       | error  Error: Cannot use GraphQLSchema "[object GraphQLSchema]" from another module or realm.
       |
       |        Ensure that there is only one instance of "graphql" in the node_modules
       |        directory. If different versions of "graphql" are the dependencies of other
       |        relied on modules, use "resolutions" to ensure only one version is installed.
       |
       |        https://yarnpkg.com/en/docs/selective-version-resolutions
       |
       |        Duplicate "graphql" modules cannot be used at the same time since different
       |        versions may have different capabilities and behavior. The data from one
       |        version used in the function from another could produce confusing and
       |        spurious results.
       |            at instanceOf (node_modules/nexus/node_modules/graphql/jsutils/instanceOf.js:28:13)
       |            at isSchema (node_modules/nexus/node_modules/graphql/type/schema.js:36:34)
       |            at assertSchema (node_modules/nexus/node_modules/graphql/type/schema.js:40:8)
       |            at validateSchema (node_modules/nexus/node_modules/graphql/type/validate.js:44:28)
       |            at assertValidSchema (node_modules/nexus/node_modules/graphql/type/validate.js:68:16)
       |            at Object.validate (node_modules/nexus/node_modules/graphql/validation/validate.js:54:35)
       |            at node_modules/nexus/src/runtime/server/handler-graphql.ts:45:30
       |            at process._tickCallback (internal/process/next_tick.js:68:7)

I think the issue might be due to the version of nexus (0.21.0-next.5) in the package.json. I tried to stick my version to 0.21.0-next.5 but was not able to make it work. I'm still not sure about the issue but would it make sense to have nexus as a peer dependency ?

Property ... does not exist on type 'string'.

Target

Modify a t.crud createPost operation like so that it automatically connect through the userId the created Post with the User table.

What i did

    t.crud.createOnePOST({
      async resolve(root, args, ctx: NexusContext, info, originalResolve) {
        console.log(JSON.stringify(args))
        const argsw = {
          data: {
            ...args.data,
            user: {
              ...args.data.user,
              connect: {
                ...args?.data?.user?.connect,
                id: ctx!.token!.userId,
              },
            },
          },
        }
        const res = await originalResolve(root, argsw, ctx, info)
        return res
      },
    })

The Functionality is fine, however i get this ugly typescript error as stated in the topic:
image

Ideas:
I think the error occurs because of the extraction of the token can't be typed?
Maybe a change type with a mapped type or something like this helps out? I'm not a typescript expert through

Thanks for your Help!

Wildcard Route Protection

Would you accept a PR for a setting to use auth on all routes?

Perhaps using this syntax
use( auth({ appSecret: process.env.TOKEN_SECRET, protectedPaths: true }) );

or

use( auth({ appSecret: process.env.TOKEN_SECRET, protectedPaths: ['Query.*', 'Mutation.*'] }) );

Network error: {"errors":[{"message":"jwt malformed"}]}

I have the following setup in my app

use(auth({
    appSecret: config.TOKEN_SECRET_KEY,
    protectedPaths
}))

However when calling my Query from a front-end app, I get the following error:

error Error: Network error: Http failure response for http://localhost:4000/graphql: 500 Internal Server Error

In the network tab of the browser i see:
{"errors":[{"message":"jwt malformed"}]}

Notes:

  • When making the call, I am not passing any Authorization Bearer token (could this be the reason of the error? if so, how can I make calls to some open queries and mutations without the need of having a user authenticated?)

Thanks!

Type definition of "token" on context not correct

From image below, the type definition of token is String | null, but when logging the object, it is actually the deserialized object. Is there a way to pass in a type/interface as a part of the setup for type-safety?

image

I'm not a typescript expert, so I don't know if its possible to stringify an interface/type, but it would be cool if we could pass our own type-string into the token definition.

image

I am new to contributing to open source projects, but I could implement something if we can come up with a good solution

Custom lib (or logic)

It would be good to let the user choose the implementation for his JWT methods (sign, verify etc).
or another lib like jose

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.