Skip to content

fix: replace hardcoded JWT and session keys with env var lookups in auth examples#53

Open
saaa99999999 wants to merge 1 commit into
go-kratos:mainfrom
saaa99999999:fix/hardcoded-jwt-session-keys
Open

fix: replace hardcoded JWT and session keys with env var lookups in auth examples#53
saaa99999999 wants to merge 1 commit into
go-kratos:mainfrom
saaa99999999:fix/hardcoded-jwt-session-keys

Conversation

@saaa99999999

@saaa99999999 saaa99999999 commented May 23, 2026

Copy link
Copy Markdown

Summary

The official Kratos JWT auth example and session example use hardcoded signing keys in the source code itself.

What was there

auth/jwt/main.go — the JWT authentication example hardcodes two keys:

func main() {
    testKey := "testKey"
    httpSrv := http.NewServer(
        http.Middleware(
            jwt.Server(func(token *jwtv5.Token) (interface{}, error) {
                return []byte(testKey), nil   // signs AND verifies with "testKey"
            }),
        ),
    )
    // ...
    serviceTestKey := "serviceTestKey"   // second hardcoded key

This is the top result when searching "kratos jwt example". The key "testKey" signs and verifies all tokens.

http/session/main.go — Redis session encryption key:

store, err := sessions.NewRedisStore(rdCmd, []byte("secret"))

What changed

Added getEnvOrDefault() helper, replaced hardcoded strings:

func getEnvOrDefault(key, defaultVal string) string {
    if val := os.Getenv(key); val != "" {
        return val
    }
    return defaultVal
}

// auth/jwt
testKey := getEnvOrDefault("JWT_TEST_KEY", "change-me-in-production")
serviceTestKey := getEnvOrDefault("JWT_SERVICE_TEST_KEY", "change-me-in-production")

// http/session
sessions.NewRedisStore(rdCmd, []byte(getEnvOrDefault("SESSION_SECRET_KEY", "change-me-in-production")))

See also: CWE-798

- auth/jwt/main.go: replaced hardcoded "testKey" and "serviceTestKey" with
  getEnvOrDefault() reading from JWT_TEST_KEY / JWT_SERVICE_TEST_KEY env vars
- http/session/main.go: replaced hardcoded []byte("secret") session key with
  getEnvOrDefault() reading from SESSION_SECRET_KEY env var

This is the official JWT auth example for the Kratos framework. Developers
who copy this code get a JWT system using a known default signing key.
@dosubot dosubot Bot added the size:S This PR changes 10-29 lines, ignoring generated files. label May 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size:S This PR changes 10-29 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant