jwt.go 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. // Copyright 2017 The etcd Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package auth
  15. import (
  16. "context"
  17. "crypto/ecdsa"
  18. "crypto/rsa"
  19. "errors"
  20. "time"
  21. jwt "github.com/dgrijalva/jwt-go"
  22. "go.uber.org/zap"
  23. )
  24. type tokenJWT struct {
  25. lg *zap.Logger
  26. signMethod jwt.SigningMethod
  27. key interface{}
  28. ttl time.Duration
  29. verifyOnly bool
  30. }
  31. func (t *tokenJWT) enable() {}
  32. func (t *tokenJWT) disable() {}
  33. func (t *tokenJWT) invalidateUser(string) {}
  34. func (t *tokenJWT) genTokenPrefix() (string, error) { return "", nil }
  35. func (t *tokenJWT) info(ctx context.Context, token string, rev uint64) (*AuthInfo, bool) {
  36. // rev isn't used in JWT, it is only used in simple token
  37. var (
  38. username string
  39. revision uint64
  40. )
  41. parsed, err := jwt.Parse(token, func(token *jwt.Token) (interface{}, error) {
  42. if token.Method.Alg() != t.signMethod.Alg() {
  43. return nil, errors.New("invalid signing method")
  44. }
  45. switch k := t.key.(type) {
  46. case *rsa.PrivateKey:
  47. return &k.PublicKey, nil
  48. case *ecdsa.PrivateKey:
  49. return &k.PublicKey, nil
  50. default:
  51. return t.key, nil
  52. }
  53. })
  54. if err != nil {
  55. if t.lg != nil {
  56. t.lg.Warn(
  57. "failed to parse a JWT token",
  58. zap.String("token", token),
  59. zap.Error(err),
  60. )
  61. } else {
  62. plog.Warningf("failed to parse jwt token: %s", err)
  63. }
  64. return nil, false
  65. }
  66. claims, ok := parsed.Claims.(jwt.MapClaims)
  67. if !parsed.Valid || !ok {
  68. if t.lg != nil {
  69. t.lg.Warn("invalid JWT token", zap.String("token", token))
  70. } else {
  71. plog.Warningf("invalid jwt token: %s", token)
  72. }
  73. return nil, false
  74. }
  75. username = claims["username"].(string)
  76. revision = uint64(claims["revision"].(float64))
  77. return &AuthInfo{Username: username, Revision: revision}, true
  78. }
  79. func (t *tokenJWT) assign(ctx context.Context, username string, revision uint64) (string, error) {
  80. if t.verifyOnly {
  81. return "", ErrVerifyOnly
  82. }
  83. // Future work: let a jwt token include permission information would be useful for
  84. // permission checking in proxy side.
  85. tk := jwt.NewWithClaims(t.signMethod,
  86. jwt.MapClaims{
  87. "username": username,
  88. "revision": revision,
  89. "exp": time.Now().Add(t.ttl).Unix(),
  90. })
  91. token, err := tk.SignedString(t.key)
  92. if err != nil {
  93. if t.lg != nil {
  94. t.lg.Warn(
  95. "failed to sign a JWT token",
  96. zap.String("user-name", username),
  97. zap.Uint64("revision", revision),
  98. zap.Error(err),
  99. )
  100. } else {
  101. plog.Debugf("failed to sign jwt token: %s", err)
  102. }
  103. return "", err
  104. }
  105. if t.lg != nil {
  106. t.lg.Info(
  107. "created/assigned a new JWT token",
  108. zap.String("user-name", username),
  109. zap.Uint64("revision", revision),
  110. zap.String("token", token),
  111. )
  112. } else {
  113. plog.Debugf("jwt token: %s", token)
  114. }
  115. return token, err
  116. }
  117. func newTokenProviderJWT(lg *zap.Logger, optMap map[string]string) (*tokenJWT, error) {
  118. var err error
  119. var opts jwtOptions
  120. err = opts.ParseWithDefaults(optMap)
  121. if err != nil {
  122. if lg != nil {
  123. lg.Warn("problem loading JWT options", zap.Error(err))
  124. } else {
  125. plog.Errorf("problem loading JWT options: %s", err)
  126. }
  127. return nil, ErrInvalidAuthOpts
  128. }
  129. var keys = make([]string, 0, len(optMap))
  130. for k := range optMap {
  131. if !knownOptions[k] {
  132. keys = append(keys, k)
  133. }
  134. }
  135. if len(keys) > 0 {
  136. if lg != nil {
  137. lg.Warn("unknown JWT options", zap.Strings("keys", keys))
  138. } else {
  139. plog.Warningf("unknown JWT options: %v", keys)
  140. }
  141. }
  142. key, err := opts.Key()
  143. if err != nil {
  144. return nil, err
  145. }
  146. t := &tokenJWT{
  147. lg: lg,
  148. ttl: opts.TTL,
  149. signMethod: opts.SignMethod,
  150. key: key,
  151. }
  152. switch t.signMethod.(type) {
  153. case *jwt.SigningMethodECDSA:
  154. if _, ok := t.key.(*ecdsa.PublicKey); ok {
  155. t.verifyOnly = true
  156. }
  157. case *jwt.SigningMethodRSA, *jwt.SigningMethodRSAPSS:
  158. if _, ok := t.key.(*rsa.PublicKey); ok {
  159. t.verifyOnly = true
  160. }
  161. }
  162. return t, nil
  163. }