簡體   English   中英

如何使用GraphQL構建經過身份驗證的查詢?

[英]How do I structure authenticated queries with GraphQL?

我正在考慮編寫一個執行以下操作的API:

  • 注冊和登錄用戶,為用戶提供身份驗證令牌
  • 創建地圖(數據示例: { name: “Quotes”, attributes: [“quote”, “author"] }
  • 創建地圖項(數據示例: { quote: "...", author: "..." }

我會像這樣構建查詢:

// return the name and id of all the user's maps
maps(authToken="…") {
  name,
  id
}

// return all the items of a single map
maps(authToken="…") {
  map(name=“Quotes") {
    items
  }
}

// OR by using the map_id
maps(authToken="…") {
  map(id=“…") {
    items
  }
}

所以,我的問題是,這是正確的還是我需要以不同的方式構建它?

我建議在GraphQL本身之外構建身份驗證,並讓您的架構邏輯處理授權。 例如,如果您使用的是express-graphql NPM模塊,則可以檢查您的cookie或HTTP Basic Auth或您想要用來獲取身份驗證令牌的任何機制,然后通過rootValue將經過身份驗證的查看器對象傳遞給架構,在查詢解析期間的每個級別都可用:

app.use('/graphql', (request, response, next) => {
  const viewer = getViewerFromRequest(); // You provide this.
  const options = {
    rootValue: {
      viewer,
    },
    schema,
  };

  return graphqlHTTP(request => options)(request, response, next);
});

然后在模式中,您可以訪問rootValue,並可以將其用於訪問控制和授權:

resolve: (parent, args, {rootValue}) => {
  const viewer = {rootValue};

  // Code that uses viewer here...
}

請注意,從graphql v0.5.0開始, resolve簽名已更改,並且在參數列表中的第3位插入了第三個“context”參數。 此參數適用於傳遞身份驗證令牌或類似內容:

resolve: (parent, args, authToken, {rootValue}) => {
  // Code that uses the auth token here...
}

我提出了一種方法,將解析器結構化為較小函數的組合,以幫助解決這個確切的問題。 你可以在這里看到完整的答案: 如何在GraphQL查詢中檢查權限和其他條件?

基本概念是,如果將解析器構造為組合在一起的小函數,則可以將不同的授權/身份驗證機制疊加在一起,並在第一個不滿足的錯誤中拋出錯誤。 這將有助於保持代碼清潔,可測試和可重用:)

同樣是的,解析器上下文是存儲身份驗證信息以及可能需要在整個解析器中使用的其他好東西的好地方。

快樂黑客!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM