4
0

restapi_auth_jwt.go 3.6 KB

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