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.

68 lines
1.7 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  1. package security
  2. import (
  3. "fmt"
  4. "net/http"
  5. "strings"
  6. "time"
  7. "github.com/chrislusf/seaweedfs/weed/glog"
  8. "github.com/golang-jwt/jwt"
  9. )
  10. type EncodedJwt string
  11. type SigningKey []byte
  12. // SeaweedFileIdClaims is created by Master server(s) and consumed by Volume server(s),
  13. // restricting the access this JWT allows to only a single file.
  14. type SeaweedFileIdClaims struct {
  15. Fid string `json:"fid"`
  16. jwt.StandardClaims
  17. }
  18. func GenJwtForVolumeServer(signingKey SigningKey, expiresAfterSec int, fileId string) EncodedJwt {
  19. if len(signingKey) == 0 {
  20. return ""
  21. }
  22. claims := SeaweedFileIdClaims{
  23. fileId,
  24. jwt.StandardClaims{},
  25. }
  26. if expiresAfterSec > 0 {
  27. claims.ExpiresAt = time.Now().Add(time.Second * time.Duration(expiresAfterSec)).Unix()
  28. }
  29. t := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
  30. encoded, e := t.SignedString([]byte(signingKey))
  31. if e != nil {
  32. glog.V(0).Infof("Failed to sign claims %+v: %v", t.Claims, e)
  33. return ""
  34. }
  35. return EncodedJwt(encoded)
  36. }
  37. func GetJwt(r *http.Request) EncodedJwt {
  38. // Get token from query params
  39. tokenStr := r.URL.Query().Get("jwt")
  40. // Get token from authorization header
  41. if tokenStr == "" {
  42. bearer := r.Header.Get("Authorization")
  43. if len(bearer) > 7 && strings.ToUpper(bearer[0:6]) == "BEARER" {
  44. tokenStr = bearer[7:]
  45. }
  46. }
  47. return EncodedJwt(tokenStr)
  48. }
  49. func DecodeJwt(signingKey SigningKey, tokenString EncodedJwt) (token *jwt.Token, err error) {
  50. // check exp, nbf
  51. return jwt.ParseWithClaims(string(tokenString), &SeaweedFileIdClaims{}, func(token *jwt.Token) (interface{}, error) {
  52. if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
  53. return nil, fmt.Errorf("unknown token method")
  54. }
  55. return []byte(signingKey), nil
  56. })
  57. }