2017-12-08 2 views
0

공개 및 비공개 쿼리 및 변형이 혼합 된 GraphQL API가 있습니다. 사용자가 자신의 데이터를 수정할 수 있도록 권한이 검사기 및 사용자가 인증 된 작업이 필요한지 여부를 확인하는 방법을 찾고 있어요.Graphql 인증 확인을위한 미들웨어

resolver 함수의 네 번째 인수 인 info에 작업의 이름을 반환하는 path.key이 포함되어있는 것으로 나타났습니다 (문서 번호 : here).

내 솔루션과 같이, 모든 리졸버 내부 검사 기능을 추가했다 :

// modify user details 
resolve: async (parent, args, { mongo: { User }, loggedUser }, info) => { 
    // auth check 
    authChecker(info.path.key, loggedUser, args.id); 

    // continue resolving 
}, 

을 그리고 다른 파일 :

function authChecker(operationName, loggedUser, userId) { 
    if (PUBLIC_OPERATIONS.includes(operationName) { 
    // public operation 
    return true; 
    } else { 
    // private operation 
    if (args.id) { 
     // private operation that requires a permission check 
     ... 
    } else { 
     // private operation that only requires user to be logged in 
     ... 
    } 
    } 
} 

기능 true를 반환 또는 조건이있는 경우 오류가 발생하거나 충족되지 않았습니다.

이것이 괜찮은 해결책인지 또는 미들웨어로 해결할 수있는 방법이 있는지 궁금해서 모든 해결 자마다 코드를 반복하지 않아도됩니다. 문제는 미들웨어를 사용할 경우 작업 이름에 액세스 할 수 없다는 것입니다. 어떤 제안?

+0

https://github.com/kriasoft/nodejs-api-starter/issues/78 –

답변

0

미들웨어 사용은 가능해야하지만 쿼리를 직접 파싱해야하기 때문에 고통 스러울 수 있습니다. 가장 깨끗한 방법은 graphql-tools과 함께 사용할 수있는 스키마 수준 확인자를 이용하는 것입니다.

const {makeExecutableSchema, addSchemaLevelResolveFunction} = require('graphql-tools') 

const schema = makeExecutableSchema({typeDefs, resolvers}) 
addSchemaLevelResolveFunction(schema, (root, args, context, info) => { 
    // check info to see if query is private and throw if user isn't authenticated 
}) 
// use the schema like normal 
app.use('/graphql', graphqlHTTP({schema})) 

해결자가 아무 것도 반환하지 않아도됩니다. 인증이 실패 할 때 거부 된 Promise를 던지거나 반환해야합니다. graphql-tools를 사용하여 스키마를 생성하는 방법에 대한 자세한 내용은 here 문서를 확인하십시오.

+0

굉장! 나는 작업을 위해 인증이 필요한지를 확인하기 위해 이것을 사용했다. 그리고 각 개별 리졸버 내부에 권한 검사기를 보관했습니다. 감사! – Norbert

관련 문제