带有Auth0 jwt身份验证的Apollo服务器

时间:2019-08-26 14:04:12

标签: jwt apollo auth0 jwt-auth

这是我的index.js。 Express + Apollo + Auth0。使用此代码,我正在检查从客户端发送的jwt是否有效。但有一个问题。它会一直检查jwt。但是,当用户首次访问该网页时,他没有jwt。我在Apollo的配置中做错了什么。

import express from 'express';
import { ApolloServer, AuthenticationError } from 'apollo-server-express';
import { typeDefs } from './data/schema';
import { resolvers } from './data/resolvers';
import jwt from 'express-jwt';
import jwks from 'jwks-rsa';
import dotenv from 'dotenv';
import db from "./models";
import jwtAuthz from 'express-jwt-authz';
import bodyParser from 'body-parser';

dotenv.config({path:'variables.env'});

const cors = require('cors');
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
app.use(cors());

const jwtCheck = jwt({
  secret: jwks.expressJwtSecret({
      cache: true,
      rateLimit: true,
      jwksRequestsPerMinute: 5,
      jwksUri: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
}),
audience: 'xxxxxxxxxxxxxxxxxx',
issuer: 'xxxxxxxxxxxxxxxxxxxxx',
algorithms: ['RS256']
});

const checkScopes = jwtAuthz(['read:all'])

app.use(jwtCheck);
const server=  new ApolloServer({
    typeDefs,
    resolvers,
    formatError: (err) => {
        // Don't give the specific errors to the client.
        if (err.message.startsWith("Database Error: ")) {
          return new Error('Internal server error');
        }
        if (err.originalError instanceof AuthenticationError) {
            return new Error('Different authentication error message!');
        }

        // Otherwise return the original error.  The error can also
        // be manipulated in other ways, so long as it's returned.
        return err;
      },
    //errores que no se envian al engine de Apollo.. es para los errores comunes
    engine: {
        rewriteError(err) {
          // Return `null` to avoid reporting `AuthenticationError`s
          if (err instanceof AuthenticationError) {
            return null;
          }
          // All other errors will be reported.
          return err;
        }
      },
   /* OLD CODE WHEN I DIDNT USE AUTH0
    context:async ({req})=>{
        const token = req.headers['authorization'];
        let currentUser = null;
        ....VALIDATE JWT
        return {user:currentUser,db}  ;
    }*/
});



server.applyMiddleware({app});
app.listen({port:9000},()=> console.log(`Server Corriendo http://localhost:9000${server.graphqlPath}`));

0 个答案:

没有答案