restapi_auth_jwt.go 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. package httpservers
  2. import (
  3. "context"
  4. "crypto/rsa"
  5. "errors"
  6. "fmt"
  7. "github.com/golang-jwt/jwt/v4"
  8. log "github.com/sirupsen/logrus"
  9. "net/http"
  10. "os"
  11. "github.com/coreos/go-oidc/v3/oidc"
  12. )
  13. var (
  14. pubKeyBytes []byte = nil
  15. pubKey *rsa.PublicKey
  16. verifier *oidc.IDTokenVerifier
  17. )
  18. func getVerifier() *oidc.IDTokenVerifier {
  19. if verifier == nil {
  20. ctx := context.TODO()
  21. config := &oidc.Config{
  22. ClientID: cfg.AuthJwtAud,
  23. }
  24. keySet := oidc.NewRemoteKeySet(ctx, cfg.AuthJwtCertsURL)
  25. verifier = oidc.NewVerifier(cfg.AuthJwtDomain, keySet, config)
  26. }
  27. return verifier
  28. }
  29. func readPublicKey() error {
  30. if pubKeyBytes != nil {
  31. return nil // Already read.
  32. }
  33. pubKeyBytes, err := os.ReadFile(cfg.AuthJwtPubKeyPath)
  34. if err != nil {
  35. return fmt.Errorf("couldn't read public key from file %s", cfg.AuthJwtPubKeyPath)
  36. }
  37. // Since the token is RSA (which we validated at the start of this function), the return type of this function actually has to be rsa.PublicKey!
  38. pubKey, err = jwt.ParseRSAPublicKeyFromPEM(pubKeyBytes)
  39. if err != nil {
  40. return fmt.Errorf("error parsing public key object (from %s)", cfg.AuthJwtPubKeyPath)
  41. }
  42. return nil
  43. }
  44. func parseJwtTokenWithKey(cookieValue string) (*jwt.Token, error) {
  45. err := readPublicKey()
  46. if err != nil {
  47. return nil, err
  48. }
  49. return jwt.Parse(cookieValue, func(token *jwt.Token) (interface{}, error) {
  50. if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
  51. return nil, fmt.Errorf(
  52. "expected token algorithm '%v' but got '%v'",
  53. jwt.SigningMethodRS256.Name,
  54. token.Header)
  55. }
  56. return pubKey, nil
  57. })
  58. }
  59. func parseJwtTokenWithoutKey(cookieValue string) (*jwt.Token, error) {
  60. return jwt.Parse(cookieValue, func(token *jwt.Token) (interface{}, error) {
  61. // Don't forget to validate the alg is what you expect:
  62. if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
  63. return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
  64. }
  65. // hmacSampleSecret is a []byte containing your secret, e.g. []byte("my_secret_key")
  66. return []byte(cfg.AuthJwtSecret), nil
  67. })
  68. }
  69. func parseJwtToken(cookieValue string) (*jwt.Token, error) {
  70. if cfg.AuthJwtPubKeyPath != "" { // activate this path only if pub key is specified
  71. return parseJwtTokenWithKey(cookieValue)
  72. } else {
  73. return parseJwtTokenWithoutKey(cookieValue)
  74. }
  75. }
  76. func getClaimsFromJwtToken(cookieValue string) (jwt.MapClaims, error) {
  77. token, err := parseJwtToken(cookieValue)
  78. if err != nil {
  79. log.Errorf("jwt parse failure: %v", err)
  80. return nil, errors.New("jwt parse failure")
  81. }
  82. if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
  83. return claims, nil
  84. } else {
  85. return nil, errors.New("jwt token isn't valid")
  86. }
  87. }
  88. func lookupClaimValueOrDefault(claims jwt.MapClaims, key string, def string) string {
  89. if val, ok := claims[key]; ok {
  90. return fmt.Sprintf("%s", val)
  91. } else {
  92. return def
  93. }
  94. }
  95. func parseJwtCookie(request *http.Request) (string, string) {
  96. cookie, err := request.Cookie(cfg.AuthJwtCookieName)
  97. if err != nil {
  98. log.Debugf("jwt cookie check %v name: %v", err, cfg.AuthJwtCookieName)
  99. return "", ""
  100. }
  101. claims, err := getClaimsFromJwtToken(cookie.Value)
  102. log.Debugf("jwt claims data: %+v", claims)
  103. if err != nil {
  104. log.Warnf("jwt claim error: %+v", err)
  105. return "", ""
  106. }
  107. username := lookupClaimValueOrDefault(claims, cfg.AuthJwtClaimUsername, "")
  108. usergroup := lookupClaimValueOrDefault(claims, cfg.AuthJwtClaimUserGroup, "")
  109. return username, usergroup
  110. }
  111. func parseJwtHeader(headerValue string) (string, string) {
  112. if headerValue == "" {
  113. log.Warnf("JWT Header is configured, but got a request with an empty JWT auth header value")
  114. return "", ""
  115. }
  116. _, err := getVerifier().Verify(context.TODO(), headerValue)
  117. if err != nil {
  118. log.Errorf("JWT Header verification error: %v", err)
  119. return "", ""
  120. }
  121. log.Debugf("JWT Header validation succeeded!")
  122. return "", ""
  123. }