restapi_auth_jwt.go 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. package httpservers
  2. import (
  3. "crypto/rsa"
  4. "errors"
  5. "fmt"
  6. "github.com/golang-jwt/jwt/v4"
  7. log "github.com/sirupsen/logrus"
  8. "net/http"
  9. "os"
  10. )
  11. var (
  12. pubKeyBytes []byte = nil
  13. pubKey *rsa.PublicKey
  14. )
  15. func readPublicKey() error {
  16. if pubKeyBytes != nil {
  17. return nil // Already read.
  18. }
  19. pubKeyBytes, err := os.ReadFile(cfg.AuthJwtPubKeyPath)
  20. if err != nil {
  21. return fmt.Errorf("couldn't read public key from file %s", cfg.AuthJwtPubKeyPath)
  22. }
  23. // 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!
  24. pubKey, err = jwt.ParseRSAPublicKeyFromPEM(pubKeyBytes)
  25. if err != nil {
  26. return fmt.Errorf("error parsing public key object (from %s)", cfg.AuthJwtPubKeyPath)
  27. }
  28. return nil
  29. }
  30. func parseJwtTokenWithKey(cookieValue string) (*jwt.Token, error) {
  31. err := readPublicKey()
  32. if err != nil {
  33. return nil, err
  34. }
  35. return jwt.Parse(cookieValue, func(token *jwt.Token) (interface{}, error) {
  36. if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
  37. return nil, fmt.Errorf(
  38. "expected token algorithm '%v' but got '%v'",
  39. jwt.SigningMethodRS256.Name,
  40. token.Header)
  41. }
  42. return pubKey, nil
  43. })
  44. }
  45. func parseJwtTokenWithoutKey(cookieValue string) (*jwt.Token, error) {
  46. return jwt.Parse(cookieValue, func(token *jwt.Token) (interface{}, error) {
  47. // Don't forget to validate the alg is what you expect:
  48. if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
  49. return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
  50. }
  51. // hmacSampleSecret is a []byte containing your secret, e.g. []byte("my_secret_key")
  52. return []byte(cfg.AuthJwtSecret), nil
  53. })
  54. }
  55. func parseJwtToken(cookieValue string) (*jwt.Token, error) {
  56. if cfg.AuthJwtPubKeyPath != "" { // activate this path only if pub key is specified
  57. return parseJwtTokenWithKey(cookieValue)
  58. } else {
  59. return parseJwtTokenWithoutKey(cookieValue)
  60. }
  61. }
  62. func getClaimsFromJwtToken(cookieValue string) (jwt.MapClaims, error) {
  63. token, err := parseJwtToken(cookieValue)
  64. if err != nil {
  65. log.Errorf("jwt parse failure: %v", err)
  66. return nil, errors.New("jwt parse failure")
  67. }
  68. if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
  69. return claims, nil
  70. } else {
  71. return nil, errors.New("jwt token isn't valid")
  72. }
  73. }
  74. func lookupClaimValueOrDefault(claims jwt.MapClaims, key string, def string) string {
  75. if val, ok := claims[key]; ok {
  76. return fmt.Sprintf("%s", val)
  77. } else {
  78. return def
  79. }
  80. }
  81. func parseJwtCookie(request *http.Request) (string, string) {
  82. cookie, err := request.Cookie(cfg.AuthJwtCookieName)
  83. if err != nil {
  84. log.Debugf("jwt cookie check %v name: %v", err, cfg.AuthJwtCookieName)
  85. return "", ""
  86. }
  87. claims, err := getClaimsFromJwtToken(cookie.Value)
  88. log.Debugf("jwt claims data: %+v", claims)
  89. if err != nil {
  90. log.Warnf("jwt claim error: %+v", err)
  91. return "", ""
  92. }
  93. username := lookupClaimValueOrDefault(claims, cfg.AuthJwtClaimUsername, "")
  94. usergroup := lookupClaimValueOrDefault(claims, cfg.AuthJwtClaimUserGroup, "")
  95. return username, usergroup
  96. }