You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

extjwt.go 1.5KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. // Copyright (c) 2020 Daniel Oaks <daniel@danieloaks.net>
  2. // Copyright (c) 2020 Shivaram Lingamneni <slingamn@cs.stanford.edu>
  3. // released under the MIT license
  4. package jwt
  5. import (
  6. "crypto/rsa"
  7. "errors"
  8. "os"
  9. "time"
  10. jwt "github.com/golang-jwt/jwt/v5"
  11. )
  12. var (
  13. ErrNoKeys = errors.New("No EXTJWT signing keys are enabled")
  14. )
  15. type MapClaims jwt.MapClaims
  16. type JwtServiceConfig struct {
  17. Expiration time.Duration
  18. Secret string
  19. secretBytes []byte
  20. RSAPrivateKeyFile string `yaml:"rsa-private-key-file"`
  21. rsaPrivateKey *rsa.PrivateKey
  22. }
  23. func (t *JwtServiceConfig) Postprocess() (err error) {
  24. t.secretBytes = []byte(t.Secret)
  25. t.Secret = ""
  26. if t.RSAPrivateKeyFile != "" {
  27. keyBytes, err := os.ReadFile(t.RSAPrivateKeyFile)
  28. if err != nil {
  29. return err
  30. }
  31. t.rsaPrivateKey, err = jwt.ParseRSAPrivateKeyFromPEM(keyBytes)
  32. if err != nil {
  33. return err
  34. }
  35. }
  36. return nil
  37. }
  38. func (t *JwtServiceConfig) Enabled() bool {
  39. return t.Expiration != 0 && (len(t.secretBytes) != 0 || t.rsaPrivateKey != nil)
  40. }
  41. func (t *JwtServiceConfig) Sign(claims MapClaims) (result string, err error) {
  42. claims["exp"] = time.Now().Unix() + int64(t.Expiration/time.Second)
  43. if t.rsaPrivateKey != nil {
  44. token := jwt.NewWithClaims(jwt.SigningMethodRS256, jwt.MapClaims(claims))
  45. return token.SignedString(t.rsaPrivateKey)
  46. } else if len(t.secretBytes) != 0 {
  47. token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims(claims))
  48. return token.SignedString(t.secretBytes)
  49. } else {
  50. return "", ErrNoKeys
  51. }
  52. }