authentication
Skill3 starsChanged 3 months agoMITView on GitHub
JWTAuth extracts the token, verifies the signature, optionally enforces claims, and stores claims in the context. Configure at least one verification mechanism: SigningSecret, RsaKey, JwksUrl, or JwksFile. Token sources — header:Authorization (a Bearer prefix is stripped), query:token, cookie:jwt. Combine them: Status codes — a missing/expired/malformed token gives 401; a token that verifies but fails ClaimsExpression or ValidateClaims gives 403. OnUnauthorized overrides both. Validate a token by hand (outside the middleware): ClaimsExpression is a string parsed into an AST. Operators: !…
20 other projects use a version of this.
Adopted by
Most recently taken up by
- codewithmukesh/dotnet-claude-kittheir own version, first seen Nov 8, 2026
- zdanovichnick/dotnet-pilottheir own version, first seen Nov 6, 2026
- psubramanian/Claude-Skillstheir own version, first seen Oct 13, 2026
- thienqo/ios-skillstheir own version, first seen Oct 11, 2026
- Resgrid/Coretheir own version, first seen Oct 8, 2026
- latitude-dev/latitude-llmtheir own version, first seen Oct 8, 2026
Used with
Projects with it also use convention-learner, opentelemetry and 9 more.
Other files people use alongside this one.
Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
codewithmukeshSkillconvention-learner
Detects and enforces project-specific coding conventions by analyzing existing codebase patterns. Learns naming conventions, folder structure, test organization, and coding style from the existing code. Load when: "conventions", "coding standards", "project patterns", "enforce style", "detect patterns", "learn conventions", "code consistency".
Also in 3 projects that use this
codewithmukeshSkillopentelemetry
OpenTelemetry observability for .NET 10 applications. Covers traces, metrics, and logs using the OpenTelemetry SDK with OTLP export. Includes custom ActivitySource, IMeterFactory metrics, resource configuration, and Aspire Dashboard integration. Load this skill when setting up distributed tracing, custom metrics, OTLP export, or when the user mentions "OpenTelemetry", "OTLP", "traces", "spans", "Activity", "ActivitySource", "metrics", "IMeterFactory", "Meter", "Counter", "Histogram", "Gauge", "telemetry", "observability", "distributed tracing", "OTEL", or "Aspire Dashboard".
Also in 3 projects that use this
MovGP0Skillmodern-csharp
Modern C# style guidance for Bendex and MicroSea code changes, including primary constructors, expression-bodied members, var usage, target-typed new, lambdas, and pattern matching.
Also in 3 projects that use this
wpankSkillcaching
Caching strategies, invalidation, eviction policies, HTTP caching, distributed caching, and anti-patterns. Use when designing cache layers, choosing eviction policies, debugging stale data, or optimizing read-heavy workloads.
Also in 5 projects that use this
MicrosoftSkillresilience
Apply resilience patterns (retry, backoff, circuit breaking) when writing or reviewing code that makes outbound HTTP/REST calls, database operations, or any I/O that can experience transient failures. Use this skill when: (1) writing new code that calls external services or APIs, (2) reviewing code that uses fetch, HTTP clients, or service-to-service calls, (3) adding queue consumers or workers that interact with remote systems, (4) debugging intermittent failures in production.
Also in 3 projects that use this
hongyuancSkillvertical-slice
Build and evaluate a production-quality vertical slice before advancing from Pre-Production to Production.
Also in 3 projects that use this
Other versions20 projects use a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 20
- BuilderIO/agent-native★ 7.6ksame name
- latitude-dev/latitude-llm★ 4.7ksame name
- codewithmukesh/dotnet-claude-kit★ 808same name
- Resgrid/Core★ 238same name
- microsoft/awesome-rayfin★ 108same name
- nahid-sparktales/agent-dispatcher★ 59same name
- autosendhq/email-skills★ 18same name
- CheehooLabs/SpureeSkills★ 18same name
- zdanovichnick/dotnet-pilot★ 5same name
- pluginagentmarketplace/custom-plugin-backend★ 4same name
10 more not listed
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository20 other files it gives its agents.
- cliSkill
- contextSkill
- dynamic_routesSkill
- error_handlingSkill
- http_clientSkill
- middlewareSkill
- openapiSkill
- overviewSkill
- request_bindingSkill
- responseSkill
- route_definitionSkill
- routingSkill
- sse_streamSkill
- std_compatSkill
- templatingSkill
- testingSkill
- tls_httpsSkill
- validationSkill
- websocketSkill
- web_spaSkill
The file
Files
Okapi Authentication & CORS
JWT Authentication
JWTAuth extracts the token, verifies the signature, optionally enforces claims, and stores claims in the context.
jwtAuth := okapi.JWTAuth{
SigningSecret: []byte("supersecret"), // HMAC (HS256/384/512)
RsaKey: publicKey, // RSA (RS256/384/512)
JwksUrl: "https://issuer.example.com/.well-known/jwks.json",
JwksFile: jwks, // from okapi.LoadJWKSFromFile(...)
Algorithms: []string{"RS256", "ES256"}, // accepted signing algorithms
Audience: "my-api", // expected "aud"
Issuer: "https://issuer.example.com", // expected "iss"
TokenLookup: "header:Authorization,cookie:jwt", // sources, tried in order
ContextKey: "user", // store the full claims under this key
ForwardClaims: map[string]string{ // copy selected claims into the store
"email": "user.email",
"role": "realm_access.roles.0",
},
ClaimsExpression: "Equals(`email_verified`, `true`) && OneOf(`user.role`, `admin`, `owner`)",
ValidateClaims: func(c *okapi.Context, claims jwt.Claims) error { return nil },
OnUnauthorized: func(c *okapi.Context) error { return c.ErrorUnauthorized("Nope") },
}
api := o.Group("/api", jwtAuth.Middleware).WithBearerAuth()Configure at least one verification mechanism: SigningSecret, RsaKey, JwksUrl, or JwksFile.
| Field | Notes |
SigningSecret []byte | HMAC key. Supersedes the deprecated SecretKey. |
RsaKey *rsa.PublicKey | RSA public key. |
JwksUrl string | Remote JWKS endpoint for key discovery. |
JwksFile *Jwks | Static JWKS from file or base64 (okapi.LoadJWKSFromFile). |
Algorithms []string | Accepted algorithms. Defaults to RS256, HS256, ES256. Supersedes the deprecated single-valued Algo. |
Audience / Issuer | Validated aud / iss claims. |
TokenLookup string | Comma-separated source:name list; the first non-empty hit wins. Default header:Authorization. |
ContextKey string | Key holding the full jwt.MapClaims. |
ForwardClaims map[string]string | contextKey -> claim.path (dot notation, numeric indices allowed). |
ClaimsExpression string | Expression DSL (below). |
ValidateClaims func(*Context, jwt.Claims) error | Custom validation; supersedes the deprecated ValidateRole. |
OnUnauthorized HandlerFunc | Custom response for any auth failure. |
Token sources — header:Authorization (a Bearer prefix is stripped), query:token, cookie:jwt. Combine them:
TokenLookup: "header:Authorization,query:token,cookie:jwt"Status codes — a missing/expired/malformed token gives 401; a token that verifies but fails ClaimsExpression or ValidateClaims gives 403. OnUnauthorized overrides both.
Validate a token by hand (outside the middleware):
claims, err := jwtAuth.ValidateToken(c) // (jwt.MapClaims, error)Claims Expression DSL
ClaimsExpression is a string parsed into an AST.
| Function | Description |
Equals(field, value) | Exact equality (compares against scalars and array members) |
Prefix(field, prefix) | String prefix match |
Contains(field, v1, v2, ...) | Field contains all listed values (substring or array membership) |
OneOf(field, v1, v2, ...) | Field equals any listed value |
Operators: ! (NOT), && (AND), || (OR) — && binds tighter than ||. Field names and literals use backticks; dot notation drills into nested claims.
ClaimsExpression: "Equals(`email_verified`, `true`) && (OneOf(`user.role`, `admin`, `owner`) || Contains(`tags`, `vip`))"Programmatic equivalents (useful for composing expressions in code):
expr := okapi.And(
okapi.Equals("email_verified", "true"),
okapi.Or(
okapi.OneOf("user.role", "admin", "owner"),
okapi.Contains("tags", "vip"),
),
)
ok, err := expr.Evaluate(claims) // claims is jwt.MapClaims
parsed, err := okapi.ParseExpression("Prefix(`sub`, `user_`) && !Equals(`banned`, `true`)")Types: AndExpr, OrExpr, NotExpr, EqualsExpr, PrefixExpr, ContainsExpr, OneOfExpr — all implement Expression.
Reading Claims in a Handler
// Full claims via ContextKey
if v, ok := c.Get("user"); ok {
claims := v.(jwt.MapClaims)
sub, _ := claims["sub"].(string)
}
// Individual forwarded claims (stored as strings)
email := c.GetString("email")
role := c.GetString("role")Custom Claim Validation
jwtAuth.ValidateClaims = func(c *okapi.Context, claims jwt.Claims) error {
mc, ok := claims.(jwt.MapClaims)
if !ok {
return errors.New("invalid claims type")
}
if v, _ := mc["email_verified"].(bool); !v {
return errors.New("email not verified")
}
return nil
}Custom Unauthorized Response
jwtAuth.OnUnauthorized = func(c *okapi.Context) error {
return c.ErrorUnauthorized("Custom unauthorized payload")
}Token Generation
token, err := okapi.GenerateJwtToken([]byte(secret), jwt.MapClaims{
"sub": "123",
"role": "admin",
}, 24*time.Hour)JWKS Loading
jwks, err := okapi.LoadJWKSFromFile("path/to/jwks.json") // also accepts a base64-encoded JWKS
jwtAuth.JwksFile = jwks
// Or discover keys remotely
jwtAuth.JwksUrl = "https://issuer.example.com/.well-known/jwks.json"Jwks holds Keys []Jwk; Jwk carries Kid, Kty, N/E (RSA) and Crv/X/Y (EC).
Basic Authentication
basicAuth := okapi.BasicAuth{
Username: "admin",
Password: "secret",
Realm: "Admin Area",
ContextKey: "user", // where the username is stored; default "username"
}
o.Use(basicAuth.Middleware) // global
admin := o.Group("/admin", basicAuth.Middleware).WithBasicAuth() // group + docs
o.Get("/dashboard", h).Use(basicAuth.Middleware) // per routeCredentials are compared in constant time; failures return 401 with a WWW-Authenticate header. (BasicAuthMiddleware is a deprecated alias of BasicAuth.)
CORS
o.WithCORS(okapi.Cors{
AllowedOrigins: []string{"https://app.example.com", "https://*.example.com"},
AllowedHeaders: []string{"Content-Type", "Authorization"},
AllowMethods: []string{"GET", "POST", "PUT", "DELETE"},
ExposeHeaders: []string{"X-Request-ID"},
Headers: map[string]string{"X-Frame-Options": "DENY"}, // extra response headers
MaxAge: 3600, // preflight cache seconds; <= 0 omits the header
AllowCredentials: true,
})
// As an option at construction
o := okapi.New(okapi.WithCors(corsConfig))Origin matching:
"*"— any origin. WithAllowCredentials: truethe request origin is echoed verbatim so credentialed requests still work."https://*.example.com"— scheme + wildcard subdomain.- Exact origins are matched case-insensitively.
Empty AllowedHeaders / AllowMethods echo back Access-Control-Request-Headers / Access-Control-Request-Method on preflight.
Real preflights (OPTIONS with Access-Control-Request-Method) are short-circuited with 204; plain OPTIONS requests fall through to your handler. The middleware can also be attached directly as corsConfig.CORSHandler.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

