hasura / go-graphql-client

Package graphql provides a GraphQL client implementation.
MIT License
395 stars 91 forks source link

How to refresh accessToken in onError #130

Closed saranonearth closed 6 months ago

saranonearth commented 6 months ago

I am currently doing the following to refresh the accessToken whenever JWTExpired error reaches onError

client := graphql.NewSubscriptionClient(config.StrongholdGraphql).
        WithConnectionParams(map[string]interface{}{
            "headers": map[string]string{
                "Authorization": token,
            },
        }).
        WithoutLogTypes(graphql.GQLData, graphql.GQLConnectionKeepAlive).
        OnError(func(sc *graphql.SubscriptionClient, err error) error {
            logger.L.Error("Error in subscription", zap.Error(err))

            // if JWT has expired then refresh the token and start subscribing again
            if strings.Contains(err.Error(), "JWTExpired") {
                authResponse, err := fetchAuthToken()
                if err != nil {
                    logger.L.Error("Error while refreshing auth token in Subscription OnError", zap.Error(err))
                    return err
                }
                sc.WithConnectionParams(map[string]interface{}{
                    "headers": map[string]string{
                        "Authorization": authResponse.AccessToken,
                    },
                })
                return sc.Run()
            }
            return sc.Run()
        })

2 Questions,

  1. Is this the right way to set the header again using WithConnectionParams()? Does sc.Run() in onError starts with the new accessToken?

  2. Getting this error

"failed to read JSON message: failed to get reader: received close frame: status = StatusCode(4400) and reason = \"{\"server_error_msg\":\"4400: Connection initialization failed: Malformed Authorization header\"}\""

hgiasac commented 6 months ago
  1. You can try to use WithConnectionParamsFn to handle dynamic tokens. The client will run this function to get the new token when reconnecting.
  2. I don't know how the server handles authentication. You should check server logs for more context, e.g invalid auth token
saranonearth commented 6 months ago

Got it. Thanks @hgiasac.