restapi_auth_jwt.go 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. package httpservers
  2. import (
  3. "context"
  4. "crypto/rsa"
  5. "errors"
  6. "fmt"
  7. "github.com/golang-jwt/jwt/v5"
  8. log "github.com/sirupsen/logrus"
  9. "net/http"
  10. "os"
  11. "strings"
  12. // "github.com/coreos/go-oidc/v3/oidc"
  13. "github.com/MicahParks/keyfunc/v3"
  14. "time"
  15. )
  16. var (
  17. pubKeyBytes []byte = nil
  18. pubKey *rsa.PublicKey
  19. jwksVerifier keyfunc.Keyfunc
  20. )
  21. func initJwks() {
  22. if jwksVerifier == nil {
  23. var err error
  24. if cfg.AuthJwtCertsURL != "" {
  25. ctx, cancel := context.WithTimeout(context.Background(), 300*time.Second)
  26. jwksVerifier, err = keyfunc.NewDefaultCtx(ctx, []string{
  27. cfg.AuthJwtCertsURL,
  28. })
  29. if err != nil {
  30. log.Errorf("Init JWKS Failure: %v", err)
  31. }
  32. defer cancel()
  33. }
  34. }
  35. }
  36. func readLocalPublicKey() error {
  37. if pubKeyBytes != nil {
  38. return nil // Already read.
  39. }
  40. pubKeyBytes, err := os.ReadFile(cfg.AuthJwtPubKeyPath)
  41. if err != nil {
  42. return fmt.Errorf("couldn't read public key from file %s", cfg.AuthJwtPubKeyPath)
  43. }
  44. // 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!
  45. pubKey, err = jwt.ParseRSAPublicKeyFromPEM(pubKeyBytes)
  46. if err != nil {
  47. return fmt.Errorf("error parsing public key object (from %s)", cfg.AuthJwtPubKeyPath)
  48. }
  49. return nil
  50. }
  51. func parseJwtTokenWithRemoteKey(jwtToken string) (*jwt.Token, error) {
  52. initJwks()
  53. return jwt.Parse(jwtToken, jwksVerifier.Keyfunc, jwt.WithAudience(cfg.AuthJwtAud))
  54. }
  55. func parseJwtTokenWithLocalKey(jwtString string) (*jwt.Token, error) {
  56. err := readLocalPublicKey()
  57. if err != nil {
  58. return nil, err
  59. }
  60. return jwt.Parse(jwtString, func(token *jwt.Token) (interface{}, error) {
  61. if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
  62. return nil, fmt.Errorf("parseJwt expected token algorithm RSA but got: %v", token.Header["alg"])
  63. }
  64. return pubKey, nil
  65. })
  66. }
  67. // Hash-based Message Authentication Code
  68. func parseJwtTokenWithHMAC(jwtString string) (*jwt.Token, error) {
  69. return jwt.Parse(jwtString, func(token *jwt.Token) (interface{}, error) {
  70. if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
  71. return nil, fmt.Errorf("parseJwt expected token algorithm HMAC but got: %v", token.Header["alg"])
  72. }
  73. return []byte(cfg.AuthJwtHmacSecret), nil
  74. })
  75. }
  76. func parseJwtToken(jwtString string) (*jwt.Token, error) {
  77. if cfg.AuthJwtCertsURL != "" {
  78. return parseJwtTokenWithRemoteKey(jwtString)
  79. }
  80. if cfg.AuthJwtPubKeyPath != "" {
  81. return parseJwtTokenWithLocalKey(jwtString)
  82. }
  83. return parseJwtTokenWithHMAC(jwtString)
  84. }
  85. func getClaimsFromJwtToken(jwtString string) (jwt.MapClaims, error) {
  86. token, err := parseJwtToken(jwtString)
  87. if err != nil {
  88. log.Errorf("jwt parse failure: %v", err)
  89. return nil, errors.New("jwt parse failure")
  90. }
  91. if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
  92. return claims, nil
  93. } else {
  94. return nil, errors.New("jwt token isn't valid")
  95. }
  96. }
  97. func lookupClaimValueOrDefault(claims jwt.MapClaims, key string, def string) string {
  98. if val, ok := claims[key]; ok {
  99. return fmt.Sprintf("%s", val)
  100. } else {
  101. return def
  102. }
  103. }
  104. func parseJwtCookie(request *http.Request) (string, string) {
  105. cookie, err := request.Cookie(cfg.AuthJwtCookieName)
  106. if err != nil {
  107. log.Debugf("jwt cookie check %v name: %v", err, cfg.AuthJwtCookieName)
  108. return "", ""
  109. }
  110. return parseJwt(cookie.Value)
  111. }
  112. func parseJwt(token string) (string, string) {
  113. claims, err := getClaimsFromJwtToken(token)
  114. if err != nil {
  115. log.Warnf("jwt claim error: %+v", err)
  116. return "", ""
  117. }
  118. if cfg.InsecureAllowDumpJwtClaims {
  119. log.Debugf("JWT Claims %+v", claims)
  120. }
  121. username := lookupClaimValueOrDefault(claims, cfg.AuthJwtClaimUsername, "")
  122. usergroup := parseGroupClaim(cfg.AuthJwtClaimUserGroup, claims)
  123. return username, usergroup
  124. }
  125. func parseGroupClaim(groupClaim string, claims jwt.MapClaims) string {
  126. usergroup := ""
  127. if val, ok := claims[groupClaim]; ok {
  128. if array, ok := val.([]interface{}); ok {
  129. groups := make([]string, len(array))
  130. for i, v := range array {
  131. groups[i] = fmt.Sprintf("%s", v)
  132. }
  133. usergroup = strings.Join(groups, " ")
  134. } else {
  135. usergroup = fmt.Sprintf("%s", val)
  136. }
  137. }
  138. return usergroup
  139. }