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.

72 lines
1.5 KiB

10 years ago
10 years ago
  1. package security
  2. import (
  3. "net/http"
  4. "strings"
  5. "time"
  6. "github.com/chrislusf/seaweedfs/weed/glog"
  7. jwt "github.com/dgrijalva/jwt-go"
  8. )
  9. type EncodedJwt string
  10. type Secret string
  11. func GenJwt(secret Secret, fileId string) EncodedJwt {
  12. if secret == "" {
  13. return ""
  14. }
  15. t := jwt.New(jwt.GetSigningMethod("HS256"))
  16. t.Claims["exp"] = time.Now().Unix() + 10
  17. t.Claims["sub"] = fileId
  18. encoded, e := t.SignedString(secret)
  19. if e != nil {
  20. glog.V(0).Infof("Failed to sign claims: %v", t.Claims)
  21. return ""
  22. }
  23. return EncodedJwt(encoded)
  24. }
  25. func GetJwt(r *http.Request) EncodedJwt {
  26. // Get token from query params
  27. tokenStr := r.URL.Query().Get("jwt")
  28. // Get token from authorization header
  29. if tokenStr == "" {
  30. bearer := r.Header.Get("Authorization")
  31. if len(bearer) > 7 && strings.ToUpper(bearer[0:6]) == "BEARER" {
  32. tokenStr = bearer[7:]
  33. }
  34. }
  35. // Get token from cookie
  36. if tokenStr == "" {
  37. cookie, err := r.Cookie("jwt")
  38. if err == nil {
  39. tokenStr = cookie.Value
  40. }
  41. }
  42. return EncodedJwt(tokenStr)
  43. }
  44. func EncodeJwt(secret Secret, claims map[string]interface{}) (EncodedJwt, error) {
  45. if secret == "" {
  46. return "", nil
  47. }
  48. t := jwt.New(jwt.GetSigningMethod("HS256"))
  49. t.Claims = claims
  50. encoded, e := t.SignedString(secret)
  51. return EncodedJwt(encoded), e
  52. }
  53. func DecodeJwt(secret Secret, tokenString EncodedJwt) (token *jwt.Token, err error) {
  54. // check exp, nbf
  55. return jwt.Parse(string(tokenString), func(token *jwt.Token) (interface{}, error) {
  56. return secret, nil
  57. })
  58. }