github.com/operandinc/gqlgen@v0.16.1/docs/content/recipes/authentication.md (about) 1 --- 2 title: "Providing authentication details through context" 3 description: How to using golang context.Context to authenticate users and pass user data to resolvers. 4 linkTitle: Authentication 5 menu: { main: { parent: "recipes" } } 6 --- 7 8 We have an app where users are authenticated using a cookie in the HTTP request, and we want to check this authentication status somewhere in our graph. Because GraphQL is transport agnostic we can't assume there will even be an HTTP request, so we need to expose these authentication details to our graph using a middleware. 9 10 ```go 11 package auth 12 13 import ( 14 "database/sql" 15 "net/http" 16 "context" 17 ) 18 19 // A private key for context that only this package can access. This is important 20 // to prevent collisions between different context uses 21 var userCtxKey = &contextKey{"user"} 22 type contextKey struct { 23 name string 24 } 25 26 // A stand-in for our database backed user object 27 type User struct { 28 Name string 29 IsAdmin bool 30 } 31 32 // Middleware decodes the share session cookie and packs the session into context 33 func Middleware(db *sql.DB) func(http.Handler) http.Handler { 34 return func(next http.Handler) http.Handler { 35 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 36 c, err := r.Cookie("auth-cookie") 37 38 // Allow unauthenticated users in 39 if err != nil || c == nil { 40 next.ServeHTTP(w, r) 41 return 42 } 43 44 userId, err := validateAndGetUserID(c) 45 if err != nil { 46 http.Error(w, "Invalid cookie", http.StatusForbidden) 47 return 48 } 49 50 // get the user from the database 51 user := getUserByID(db, userId) 52 53 // put it in context 54 ctx := context.WithValue(r.Context(), userCtxKey, user) 55 56 // and call the next with our new context 57 r = r.WithContext(ctx) 58 next.ServeHTTP(w, r) 59 }) 60 } 61 } 62 63 // ForContext finds the user from the context. REQUIRES Middleware to have run. 64 func ForContext(ctx context.Context) *User { 65 raw, _ := ctx.Value(userCtxKey).(*User) 66 return raw 67 } 68 ``` 69 70 **Note:** `getUserByID` and `validateAndGetUserID` have been left to the user to implement. 71 72 Now when we create the server we should wrap it in our authentication middleware: 73 74 ```go 75 package main 76 77 import ( 78 "net/http" 79 80 "github.com/operandinc/gqlgen/_examples/starwars" 81 "github.com/operandinc/gqlgen/graphql/handler" 82 "github.com/operandinc/gqlgen/graphql/playground" 83 "github.com/go-chi/chi" 84 ) 85 86 func main() { 87 router := chi.NewRouter() 88 89 router.Use(auth.Middleware(db)) 90 91 srv := handler.NewDefaultServer(starwars.NewExecutableSchema(starwars.NewResolver())) 92 router.Handle("/", playground.Handler("Starwars", "/query")) 93 router.Handle("/query", srv) 94 95 err := http.ListenAndServe(":8080", router) 96 if err != nil { 97 panic(err) 98 } 99 } 100 ``` 101 102 And in our resolvers (or directives) we can call `ForContext` to retrieve the data back out: 103 104 ```go 105 106 func (r *queryResolver) Hero(ctx context.Context, episode Episode) (Character, error) { 107 if user := auth.ForContext(ctx) ; user == nil || !user.IsAdmin { 108 return Character{}, fmt.Errorf("Access denied") 109 } 110 111 if episode == EpisodeEmpire { 112 return r.humans["1000"], nil 113 } 114 return r.droid["2001"], nil 115 } 116 ``` 117 118 ### Websockets 119 120 If you need access to the websocket init payload we can do the same thing with the WebsocketInitFunc: 121 122 ```go 123 func main() { 124 router := chi.NewRouter() 125 126 router.Use(auth.Middleware(db)) 127 128 router.Handle("/", handler.Playground("Starwars", "/query")) 129 router.Handle("/query", 130 handler.GraphQL(starwars.NewExecutableSchema(starwars.NewResolver())), 131 WebsocketInitFunc(func(ctx context.Context, initPayload InitPayload) (context.Context, error) { 132 userId, err := validateAndGetUserID(payload["token"]) 133 if err != nil { 134 return nil, err 135 } 136 137 // get the user from the database 138 user := getUserByID(db, userId) 139 140 // put it in context 141 userCtx := context.WithValue(r.Context(), userCtxKey, user) 142 143 // and return it so the resolvers can see it 144 return userCtx, nil 145 })) 146 ) 147 148 err := http.ListenAndServe(":8080", router) 149 if err != nil { 150 panic(err) 151 } 152 } 153 ``` 154 155 > Note 156 > 157 > Subscriptions are long lived, if your tokens can timeout or need to be refreshed you should keep the token in 158 > context too and verify it is still valid in `auth.ForContext`.