jwt.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package security
  2. import (
  3. "fmt"
  4. "net/http"
  5. "strings"
  6. "time"
  7. "github.com/chrislusf/seaweedfs/weed/util/log"
  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, expiresAfterSec int, fileId string) EncodedJwt {
  17. if len(signingKey) == 0 {
  18. return ""
  19. }
  20. claims := SeaweedFileIdClaims{
  21. fileId,
  22. jwt.StandardClaims{},
  23. }
  24. if expiresAfterSec > 0 {
  25. claims.ExpiresAt = time.Now().Add(time.Second * time.Duration(expiresAfterSec)).Unix()
  26. }
  27. t := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
  28. encoded, e := t.SignedString([]byte(signingKey))
  29. if e != nil {
  30. log.Infof("Failed to sign claims %+v: %v", t.Claims, e)
  31. return ""
  32. }
  33. return EncodedJwt(encoded)
  34. }
  35. func GetJwt(r *http.Request) EncodedJwt {
  36. // Get token from query params
  37. tokenStr := r.URL.Query().Get("jwt")
  38. // Get token from authorization header
  39. if tokenStr == "" {
  40. bearer := r.Header.Get("Authorization")
  41. if len(bearer) > 7 && strings.ToUpper(bearer[0:6]) == "BEARER" {
  42. tokenStr = bearer[7:]
  43. }
  44. }
  45. return EncodedJwt(tokenStr)
  46. }
  47. func DecodeJwt(signingKey SigningKey, tokenString EncodedJwt) (token *jwt.Token, err error) {
  48. // check exp, nbf
  49. return jwt.ParseWithClaims(string(tokenString), &SeaweedFileIdClaims{}, func(token *jwt.Token) (interface{}, error) {
  50. if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
  51. return nil, fmt.Errorf("unknown token method")
  52. }
  53. return []byte(signingKey), nil
  54. })
  55. }