Passport.js plugin for GraphQL Factory
npm install graphql-factory-passportThis plugin allows the use of passport.js standard strategies for auth to "tagged" graphql operations using the graphql-factory framework. This plugin was written
as a companion plugin to graphql-factory-acl which provides authorization to graphql
operations.
``js
import * as graphql from 'graphql'
import GraphQLFactory from 'graphql-factory'
import PassportPlugin from 'graphql-factory-passport'
import passport from 'passport'
// passport local strategy
import localStrategy from './localStrategy'
// add the strategy with a name that will be referenced
// in the _factoryPassport tag
passport.use('local', localStrategy)
const definition = {
schemas: {
Auth: {
query: {
fields: {
basicAuth: {
type: 'String',
args: {
username: { type: 'String', nullable: false },
password: { type: 'String', nullable: false }
},
resolve (source, args, context, info) {
// the user object is passed as the source
// on successful authentication
return source.username
},
// tag the field with _factoryPassport who's
// value is the strategy name
_factoryPassport: 'local'
}
}
}
}
}
}
const factory = GraphQLFactory(graphql)
const lib = factory.make(definition, {
plugin: [ new PassportPlugin(passport) ]
})
lib.Auth(
query Authenticate {
basicAuth (
username: "john",
password: "p@ncakes!"
)
})`
.then(result => {
// process query result
})
Passport should be setup the same way it is with express except that passport.initialize()
should not be called. Additionally, strategies need to be named in order for the plugin to
apply them.
For graphql operations that require passport authentication simply add _factoryPassport
key/tag to the operation's field with the strategy name as its value (see example above).
The user object is made available in the source field of the resolver function
Some passport options like redirect are ignored by this plugin because they do not make graphql
sense in the context of a request.
As previously stated this plugin can be used along with graphql-factory-acl to provide authN and authZ. The workflow there would be to create a query that uses graphql-factory-passport to authenticate a user account and return a jsonwebtoken whichgraphql-factory-acl
can then be used on operations protected by by injecting the jsonwebtoken into the rootValue.jwt` property of the request.