亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 JWT 的 GraphQL Golang 身份驗證

使用 JWT 的 GraphQL Golang 身份驗證

Go
慕娘9325324 2022-05-23 17:44:44
我有一個我一直在編寫的 GraphQL API,并且想知道當您已經在使用傳遞數據源go時如何管理 JWT 身份驗證。contextmain所以我的函數的縮寫版本是:import (    "net/http"    "github.com/graphql-go/graphql"    gqlhandler "github.com/graphql-go/handler")func queryHandler(ds *sources.DataSources, gql *gqlhandler.Handler) http.Handler {    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {        ctx := context.WithValue(context.Background(), sources.CtxSourcesKey, ds)        gql.ContextHandler(ctx, w, r)    })}func main() {    apiSchema, _ := schema.CompileSchema(schema.QueryType, schema.MutationType)    gql := gqlhandler.New(&gqlhandler.Config{        Schema:     &apiSchema,        GraphiQL:   !isDeployed,        Pretty:     false,        Playground: false,    })    http.ListenAndServe(":41000", util.CreateChiRouter(healthCheckHandler(), queryHandler(ctxSources, gql)))}如您所見,我已經創建了一個新context實例來存儲我的各種數據源的映射并將其傳遞給查詢解析函數,但還需要能夠解析出Authorization可能的 JWT 的標頭以傳遞給認證的路由。鑒于我目前的情況,最好的方法是什么?(將 JWT 與數據源上下文相結合?以不同方式處理數據源以釋放context?)
查看完整描述

1 回答

?
慕田峪7331174

TA貢獻1828條經驗 獲得超13個贊

處理此類身份驗證標頭的常用方法是使用中間件來處理身份驗證,并將身份驗證信息添加到當前上下文中。


目前,您正在創建一個新的上下文。我建議使用現有的 HTTP 上下文并添加到其中,這樣您就可以鏈接:


ctx := context.WithValue(r.Context(), sources.CtxSourcesKey, ds)

newReq:=r.WithContext(ctx)

gql.ContextHandler(ctx, w, newReq)

您可以安裝一個執行相同操作的中間件:


type autoInfoKeyType int


const authInfoKey authInfoKeyType=iota


func GetAuthInfo(ctx context.Context) *AuthInfo {

   if v:=ctx.Value(authInfoKey); v!=nil {

     return v.(*AuthInfo)

   }

   return nil

}


func AuthMiddleware(next http.Handler) http.Handler {

  return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {

    authInfo:=processJWT(...)

    if authInfo!=nil {

       ctx := context.WithValue(r.Context(), authInfoKey, authInfo)

       r=r.WithContext(ctx)

    }

    next.ServeHTTP(w,r)

  }

}

這樣,您可以檢查上下文是否具有身份驗證信息,如果有,請使用它。


if authInfo:=GetAuthInfo(req.Context()); authInfo!=nil {

  ...

}


查看完整回答
反對 回復 2022-05-23
  • 1 回答
  • 0 關注
  • 188 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號