<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: hasusozam</title>
    <description>The latest articles on DEV Community by hasusozam (@hasusozam).</description>
    <link>https://dev.to/hasusozam</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F103048%2F7feb1abf-9d74-4ce4-afe8-10e521b9597f.png</url>
      <title>DEV Community: hasusozam</title>
      <link>https://dev.to/hasusozam</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/hasusozam"/>
    <language>en</language>
    <item>
      <title>Passport JWT with GraphQL (Apollo Server 2)</title>
      <dc:creator>hasusozam</dc:creator>
      <pubDate>Thu, 20 Sep 2018 16:48:45 +0000</pubDate>
      <link>https://dev.to/hasusozam/passport-jwt-with-graphql-3gdj</link>
      <guid>https://dev.to/hasusozam/passport-jwt-with-graphql-3gdj</guid>
      <description>&lt;p&gt;I was studying and reading about authentication in GraphQL and people told me (devs from Docker and Facebook) that GraphQL doesn't need to know anything about authentication, in fact your schemas and resolvers should be simple and thin, the authentication must be done outside GraphQL, and for that I did this simple Passport JWT authentication in GraphQL to show what I understood about that.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import express from 'express'
import { ApolloServer } from 'apollo-server-express'

// ...
import passport from 'passport'
import passportJWT from 'passport-jwt'
import jwt from 'jsonwebtoken'
// ...

import schema from './schemas'

const { GRAPHQL_PORT, JWT_SECRET } = process.env

// ...
const users = [
  {
    id: 1,
    name: 'John',
    email: 'john@mail.com',
    password: 'john123'
  }
]

// generate a jwt token for testing purposes
console.log(jwt.sign(users[0], JWT_SECRET))

// ...

const { Strategy, ExtractJwt } = passportJWT

const params = {
  secretOrKey: JWT_SECRET,
  jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken()
}

const strategy = new Strategy(params, (payload, done) =&amp;gt; {
  const user = users.find(user =&amp;gt; user.id === payload.id) || null

  return done(null, user)
})

passport.use(strategy)

// ...

const app = express()

// ...

passport.initialize()

app.use('/graphql', (req, res, next) =&amp;gt; {
  passport.authenticate('jwt', { session: false }, (err, user, info) =&amp;gt; {
    if (user) {
      req.user = user
    }

    next()
  })(req, res, next)
})

// ...

const server = new ApolloServer({
  schema,
  context: ({ req }) =&amp;gt; ({
    user: req.user
  })
})

server.applyMiddleware({
  app
})

app.listen(
  {
    port: GRAPHQL_PORT
  },
  () =&amp;gt; console.log(`The GraphQL server is running on port ${GRAPHQL_PORT}`)
)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now the resolvers will have the user authenticated, but the resolvers are not responsible to make auth verification, so instead it's probably better to make a schema directive to check for authentication or even passing the current user to some kind of service in the backend to check instead of &lt;code&gt;if (user) {...&lt;/code&gt; in the resolvers.&lt;/p&gt;

&lt;p&gt;What are your thoughts about the code, any room for improvement?&lt;/p&gt;

</description>
      <category>jwt</category>
      <category>graphql</category>
      <category>authentication</category>
      <category>node</category>
    </item>
  </channel>
</rss>
