Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

extjwt.go 1.8KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. "crypto/x509"
  8. "encoding/pem"
  9. "errors"
  10. "fmt"
  11. "os"
  12. "time"
  13. "github.com/dgrijalva/jwt-go"
  14. )
  15. var (
  16. ErrNoKeys = errors.New("No signing keys are enabled")
  17. )
  18. type MapClaims jwt.MapClaims
  19. type JwtServiceConfig struct {
  20. Expiration time.Duration
  21. Secret string
  22. secretBytes []byte
  23. RSAPrivateKeyFile string `yaml:"rsa-private-key-file"`
  24. rsaPrivateKey *rsa.PrivateKey
  25. }
  26. func (t *JwtServiceConfig) Postprocess() (err error) {
  27. t.secretBytes = []byte(t.Secret)
  28. t.Secret = ""
  29. if t.RSAPrivateKeyFile != "" {
  30. keyBytes, err := os.ReadFile(t.RSAPrivateKeyFile)
  31. if err != nil {
  32. return err
  33. }
  34. d, _ := pem.Decode(keyBytes)
  35. if err != nil {
  36. return err
  37. }
  38. t.rsaPrivateKey, err = x509.ParsePKCS1PrivateKey(d.Bytes)
  39. if err != nil {
  40. privateKey, err := x509.ParsePKCS8PrivateKey(d.Bytes)
  41. if err != nil {
  42. return err
  43. }
  44. if rsaPrivateKey, ok := privateKey.(*rsa.PrivateKey); ok {
  45. t.rsaPrivateKey = rsaPrivateKey
  46. } else {
  47. return fmt.Errorf("Non-RSA key type for extjwt: %T", privateKey)
  48. }
  49. }
  50. }
  51. return nil
  52. }
  53. func (t *JwtServiceConfig) Enabled() bool {
  54. return t.Expiration != 0 && (len(t.secretBytes) != 0 || t.rsaPrivateKey != nil)
  55. }
  56. func (t *JwtServiceConfig) Sign(claims MapClaims) (result string, err error) {
  57. claims["exp"] = time.Now().Unix() + int64(t.Expiration/time.Second)
  58. if t.rsaPrivateKey != nil {
  59. token := jwt.NewWithClaims(jwt.SigningMethodRS256, jwt.MapClaims(claims))
  60. return token.SignedString(t.rsaPrivateKey)
  61. } else if len(t.secretBytes) != 0 {
  62. token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims(claims))
  63. return token.SignedString(t.secretBytes)
  64. } else {
  65. return "", ErrNoKeys
  66. }
  67. }