How to cache the authentication using auth_check middleware with goplugin?


We are using username/password in the request header to hit the Tyk and our go plugin runs in auth_check middleware that validates the request and then middleware will set an Authorization header JWT token in the request that will be used by upstream for authentication.

we want to cache the authentication done by the go plugin to avoid hitting authentication middleware for each request.

we tried using this approach it’s not working

	extractorDeadline := time.Now().Add(time.Second * 20).Unix()
	userSession := &user.SessionState {
		IdExtractorDeadline: extractorDeadline,
		LastUpdated:         time.Now().String(),
		MetaData: map[string]interface{}{
			"token": token,
        ctx.SetSession(r, userSession, true, true)

is there any other way to cache the auth?

1 Like

Hello @ibuar, and welcome to the community! :tada:

The id_extractor doesn’t work for native go plugins. Is your go plugin a native one?
It works for gRPC-based plugins, Python and Lua.
You can consider wrapping your plugin as gRPC so it caches as expected. Here’s a sample gRPC-based go plugin: custom-plugins/plugins/grpc_go-auth-pre_headerinject_authhook at master · TykTechnologies/custom-plugins · GitHub

We have internal tickets to extend its functionality to support native go plugins as well as update our documentation so it’s clearer what it supports and doesn’t.

Hope this helps.

1 Like

Thanks for the reply @Ubong

I have a few questions

  1. if we wrap it as a gRPC plugin then we need to host it in some server or can be included in Tyk Gateway itself
  2. If we use the gRPC plugin then we need to use coprocess as authentication in auth type and pass the URL for the gRPC server right?
  3. if we cache the authentication, how will that token generated in the plugin be set in the request header for the request using the auth cache?


  1. It’ll need to be on a server. Can’t be included in Tyk Gateway.

  2. Yes, you’ll need to use coprocess as authentication in auth type.

You’ll configure the URL for the gRPC server on the Gateway level. Here’s some documentation for your reference: How to write gRPC Plugins
In the API definition, the value for your Target URL will remain your target URL (not the gRPC server URL).

  1. Modifying request headers can be done by such plugins. Check out another sample gRPC-based authentication go plugin that has similar specifics.GitHub - TykTechnologies/tyk-grpc-go-basicauth-jwt: Custom BasicAuth with JWT to Upstream
    In this particular example, the plugin generates and stores the JWT inside the session metadata.
    And then the Gateway in the Global Header transform pulls the JWT from the session metadata and injects it into the header for use by the upstream.

I think this would fit your scenario exactly?
See here for more info on ID_extractor: ID Extractor