Authorization example using directive #1875
-
Is there an example of how to use gqlgen with authorization in a directive? I'm receiving a JWT token in the request. I'm using I want to check if the user permissions match the ones in the directive. Thank you very much |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
@theprobugmaker I believe I created mine based on the official docs here If you follow the example you should be able to arrive to this. c := generated.Config{
Resolvers: gql.NewResolver(),
}
// Schema Directive - @isAuthenticated
c.Directives.IsAuthenticated = func(ctx context.Context, obj interface{}, next graphql.Resolver) (res interface{}, err error) {
ctxUserID := ctx.Value(utils.ProjectContextKeys.UserCtxKey)
if ctxUserID == nil {
return nil, common.GqlUnauthorizedError(ctx)
}
return next(ctx)
}
h := handler.GraphQL(generated.NewExecutableSchema(c))
return func(c *gin.Context) {
h.ServeHTTP(c.Writer, c.Request)
}
```
on your middleware that checks token you should also inject the user in the context so this directive and your resolvers have access to it. I assume you have this done too, otherwise happy to share more code. |
Beta Was this translation helpful? Give feedback.
-
We only want get JWT token from header. How to do it? @theprobugmaker |
Beta Was this translation helpful? Give feedback.
@theprobugmaker I believe I created mine based on the official docs here
If you follow the example you should be able to arrive to this.