Skip to content

Conversation

sedkis
Copy link
Contributor

@sedkis sedkis commented Sep 23, 2025

User description

Contributor checklist

  • Reviewed PR Code suggestions and updated accordingly
  • Tyklings: Labled the PR with the relevant releases
  • Tyklings: Added Jira DX PR ticket to the subject

New Contributors



PR Type

Documentation


Description

  • Revamp custom auth plugin section

  • Add identity and session usage notes

  • Document custom rate limiting pattern

  • Explain key persistence with SetSession


Diagram Walkthrough

flowchart LR
  Auth["Custom auth (Golang plugin)"] -- "create SessionState" --> Session["SessionState with KeyID/MetaData"]
  Session -- "ctx.SetSession(...)" --> Gateway["Tyk Gateway"]
  Gateway -- "rate/quotas" --> Limits["Rate limiter & quotas"]
  Session -- "optional persist=true" --> Storage["Local DP Redis persistence"]
Loading

File Walkthrough

Relevant files
Documentation
golang.md
Expanded guidance for Golang custom authentication plugins

tyk-docs/content/api-management/plugins/golang.md

  • Rename and simplify custom auth heading.
  • Add example: attach SessionState and identity.
  • Document custom rate limiting via MetaData rate_limit_pattern.
  • Explain key persistence using ctx.SetSession persist flag.
+76/-5   

Copy link
Contributor

⚠️ Deploy preview for PR #6963 did not become live after 3 attempts.
Please check Netlify or try manually: Preview URL

Copy link
Contributor

PR Reviewer Guide 🔍

Here are some key observations to aid the review process:

⏱️ Estimated effort to review: 2 🔵🔵⚪⚪⚪
🧪 No relevant tests
🔒 No security concerns identified
⚡ Recommended focus areas for review

Clarity

The new heading "Custom Authentication Golang Plugins" replaces previous guidance about using the "auth_check" middleware and Post Authentication Hook; ensure readers still understand the need to bind the middleware correctly and when to set session persistence.

## Custom Authentication Golang Plugins

You can implement your own authentication method, written in Golang.

Let's have a look at the code example. Imagine we need to implement a very trivial authentication method when only one key is supported (in the real world you would want to store your keys in some storage or have some more complex logic).
Accuracy

The note states that providing "rate_limit_pattern" becomes the new identity for both rate-limit and quota; verify this behavior across Gateway versions and note any version constraints or caveats (e.g., analytics identity, key hashing).

### Custom Rate Limiting

- By default, Tyk derives the rate limiter key from `session.KeyID`.
- If you want a custom limiter key, set `session.MetaData["rate_limit_pattern"]` to a string. Tyk will evaluate it (supports `$tyk_meta.*` and `$tyk_context.*`) and use the resulting value as both the rate-limit key and quota key.

```go
// Custom limiter/quota key example
	sessionObject = &user.SessionState{
		OrgID: requestedAPI.OrgID,
		Rate:  2,
		Per:   5,
		MetaData: map[string]interface{}{
      // A counter is created for each "rate_limit_pattern".
      // This becomes your new identity.
			"rate_limit_pattern": realIp,
		},
	}

Notes:

  • If you provide rate_limit_pattern, Tyk uses that value directly (no auto-hashing). If you need hashing, hash it in your plugin before assigning.

</details>

<details><summary><a href='https://github.com/TykTechnologies/tyk-docs/pull/6963/files#diff-0c36572e2685d145460b6acda22c4249165e6b52ccb9736e3e4a28974d7fc6eeR1094-R1105'><strong>Persistence Scope</strong></a>

The statement about SetSession(..., true) persisting only to local Data Plane Redis could confuse multi-DP setups; consider clarifying implications for sharded/clustered Redis and key lifecycle/cleanup.
</summary>

```markdown
### Persisting the key

By default -- custom auth keys aren't persisted beyond what's necessary to track rate limits, quotas, analytics, and so on.  
However -- you may choose to persist the keys in the custom plugin.

```go
// Set session state using session object
ctx.SetSession(r, sessionObject, true)

The third argument in the parameter instructs the Gateway to save/persist the key. Note -- this isn't a global operation -- this would be scoped to the local Data Plane's redis.


</details>

</td></tr>
</table>

Copy link
Contributor

PR Code Suggestions ✨

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
Possible issue
Prevent global rate-limiting fallback

Warn that leaving KeyID empty applies limits globally across requestors. Add a guard
to ensure identity is non-empty before setting the session to avoid accidental
global throttling.

tyk-docs/content/api-management/plugins/golang.md [1053-1065]

+if identity == "" {
+    http.Error(rw, "unauthorized", http.StatusUnauthorized)
+    return
+}
 s := &user.SessionState{
     OrgID: "default",
-    // This is the default way that Tyk will track your identities.
-    // Using "KeyID".
-    // Usually, this should be set, otherwise, the below 
-    // rate limits will be applied globally across all API requestors.
-    KeyID: identity, // identity used for bucketing (via hash)
-    Rate:  100,      // 100 requests
-    Per:   60,       // per 60 seconds
-    // Optional quotas
+    KeyID: identity,
+    Rate:  100,
+    Per:   60,
     // QuotaMax:         10000,
     // QuotaRenewalRate: 86400,
 }
Suggestion importance[1-10]: 7

__

Why: The guard against empty identity aligns with the snippet's warning that empty KeyID applies limits globally; adding a simple check improves correctness and avoids unintended global throttling. It's a meaningful but straightforward improvement.

Medium
General
Document backward-compatible call

The SetSession signature shown omits the API key parameter that may be required on
older Gateway versions. Add a brief note showing the alternative call for backward
compatibility to prevent runtime mismatches.

tyk-docs/content/api-management/plugins/golang.md [1068]

+// For Gateway >= 4.0.1
 ctx.SetSession(r, s, false)
+// For older Gateways, use:
+// ctx.SetSession(r, s, identity, true)
Suggestion importance[1-10]: 6

__

Why: The note about older Gateway SetSession signature is accurate given prior docs removed such guidance; adding the alternative prevents runtime mismatches on older versions. Impact is moderate since it's a documentation clarification rather than a functional fix.

Low
Enforce string type for limiter key

Clarify that rate_limit_pattern must be a string; passing non-string types (like
net.IP) can lead to unexpected keys. Show explicit conversion to string for safety.

tyk-docs/content/api-management/plugins/golang.md [1079-1088]

 sessionObject = &user.SessionState{
     OrgID: requestedAPI.OrgID,
     Rate:  2,
     Per:   5,
     MetaData: map[string]interface{}{
-      // A counter is created for each "rate_limit_pattern".
-      // This becomes your new identity.
-        "rate_limit_pattern": realIp,
+        "rate_limit_pattern": realIp.String(), // ensure string
     },
 }
Suggestion importance[1-10]: 6

__

Why: Clarifying rate_limit_pattern should be a string and showing realIp.String() helps prevent subtle bugs from non-string types being stored, improving reliability. The change is correct and useful but not critical.

Low

@sedkis sedkis requested a review from sharadregoti September 23, 2025 14:22
Copy link

netlify bot commented Sep 23, 2025

PS. Add to the end of url /docs/nightly

Name Link
🔨 Latest commit c268150
🔍 Latest deploy log https://app.netlify.com/projects/tyk-docs/deploys/68d51c6f8b590e0007dea33f
😎 Deploy Preview https://deploy-preview-6963--tyk-docs.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify project configuration.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants