restapi_auth_jwt.go 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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 parseJwtToken(cookieValue string) (*jwt.Token, error) {
  16. if cfg.AuthJwtPubKeyPath != "" { // activate this path only if pub key is specified
  17. if pubKeyBytes == nil { // keep in memory after first load
  18. var err error
  19. pubKeyBytes, err = os.ReadFile(cfg.AuthJwtPubKeyPath)
  20. if err != nil {
  21. return nil, 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 nil, fmt.Errorf("error parsing public key object (from %s)", cfg.AuthJwtPubKeyPath)
  27. }
  28. }
  29. return jwt.Parse(cookieValue, func(token *jwt.Token) (interface{}, error) {
  30. if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
  31. return nil, fmt.Errorf(
  32. "expected token algorithm '%v' but got '%v'",
  33. jwt.SigningMethodRS256.Name,
  34. token.Header)
  35. }
  36. return pubKey, nil
  37. })
  38. }
  39. return jwt.Parse(cookieValue, func(token *jwt.Token) (interface{}, error) {
  40. // Don't forget to validate the alg is what you expect:
  41. if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
  42. return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
  43. }
  44. // hmacSampleSecret is a []byte containing your secret, e.g. []byte("my_secret_key")
  45. return []byte(cfg.AuthJwtSecret), nil
  46. })
  47. }
  48. func getClaimsFromJwtToken(cookieValue string) (jwt.MapClaims, error) {
  49. token, err := parseJwtToken(cookieValue)
  50. if err != nil {
  51. log.Errorf("jwt parse failure: %v", err)
  52. return nil, errors.New("jwt parse failure")
  53. }
  54. if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
  55. return claims, nil
  56. } else {
  57. return nil, errors.New("jwt token isn't valid")
  58. }
  59. }
  60. func lookupClaimValueOrDefault(claims jwt.MapClaims, key string, def string) string {
  61. if val, ok := claims[key]; ok {
  62. return fmt.Sprintf("%s", val)
  63. } else {
  64. return def
  65. }
  66. }
  67. func parseJwtCookie(request *http.Request) (string, string) {
  68. cookie, err := request.Cookie(cfg.AuthJwtCookieName)
  69. if err != nil {
  70. log.Debugf("jwt cookie check %v name: %v", err, cfg.AuthJwtCookieName)
  71. return "", ""
  72. }
  73. claims, err := getClaimsFromJwtToken(cookie.Value)
  74. log.Debugf("jwt claims data: %+v", claims)
  75. if err != nil {
  76. log.Warnf("jwt claim error: %+v", err)
  77. return "", ""
  78. }
  79. username := lookupClaimValueOrDefault(claims, cfg.AuthJwtClaimUsername, "")
  80. usergroup := lookupClaimValueOrDefault(claims, cfg.AuthJwtClaimUserGroup, "")
  81. return username, usergroup
  82. }