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.

65 lines
1.4 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. jwt "github.com/dgrijalva/jwt-go"
  9. )
  10. type EncodedJwt string
  11. type SigningKey []byte
  12. type SeaweedFileIdClaims struct {
  13. Fid string `json:"fid"`
  14. jwt.StandardClaims
  15. }
  16. func GenJwt(signingKey SigningKey, fileId string) EncodedJwt {
  17. if len(signingKey) == 0 {
  18. return ""
  19. }
  20. claims := SeaweedFileIdClaims{
  21. fileId,
  22. jwt.StandardClaims{
  23. ExpiresAt: time.Now().Add(time.Second * 10).Unix(),
  24. },
  25. }
  26. t := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
  27. encoded, e := t.SignedString([]byte(signingKey))
  28. if e != nil {
  29. glog.V(0).Infof("Failed to sign claims %+v: %v", t.Claims, e)
  30. return ""
  31. }
  32. return EncodedJwt(encoded)
  33. }
  34. func GetJwt(r *http.Request) EncodedJwt {
  35. // Get token from query params
  36. tokenStr := r.URL.Query().Get("jwt")
  37. // Get token from authorization header
  38. if tokenStr == "" {
  39. bearer := r.Header.Get("Authorization")
  40. if len(bearer) > 7 && strings.ToUpper(bearer[0:6]) == "BEARER" {
  41. tokenStr = bearer[7:]
  42. }
  43. }
  44. return EncodedJwt(tokenStr)
  45. }
  46. func DecodeJwt(signingKey SigningKey, tokenString EncodedJwt) (token *jwt.Token, err error) {
  47. // check exp, nbf
  48. return jwt.ParseWithClaims(string(tokenString), &SeaweedFileIdClaims{}, func(token *jwt.Token) (interface{}, error) {
  49. if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
  50. return nil, fmt.Errorf("unknown token method")
  51. }
  52. return []byte(signingKey), nil
  53. })
  54. }