1.4.0 • Published 4 years ago

nexus-plugin-jwt-auth v1.4.0

Weekly downloads
661
License
MIT
Repository
-
Last release
4 years ago

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 account = 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

1.4.0

4 years ago

1.3.1

4 years ago

1.3.0

4 years ago

1.2.0

4 years ago

1.1.1

4 years ago

1.1.0

4 years ago

1.0.0

4 years ago

1.0.0-beta-1

4 years ago

0.0.16

4 years ago

0.0.17

4 years ago

0.0.15

4 years ago

0.0.14

4 years ago

0.0.13

4 years ago

0.0.12

4 years ago

0.0.11

4 years ago

0.0.10

4 years ago

0.0.9

4 years ago

0.0.8

4 years ago

0.0.7

4 years ago

0.0.6

4 years ago

0.0.5

4 years ago

0.0.4

4 years ago

0.0.3

4 years ago

0.0.2

4 years ago

0.0.1

4 years ago