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.

74 lines
1.5 KiB

10 years ago
10 years ago
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 = &jwt.StandardClaims{
  17. ExpiresAt: time.Now().Add(time.Second * 10).Unix(),
  18. Subject: fileId,
  19. }
  20. encoded, e := t.SignedString(secret)
  21. if e != nil {
  22. glog.V(0).Infof("Failed to sign claims: %v", t.Claims)
  23. return ""
  24. }
  25. return EncodedJwt(encoded)
  26. }
  27. func GetJwt(r *http.Request) EncodedJwt {
  28. // Get token from query params
  29. tokenStr := r.URL.Query().Get("jwt")
  30. // Get token from authorization header
  31. if tokenStr == "" {
  32. bearer := r.Header.Get("Authorization")
  33. if len(bearer) > 7 && strings.ToUpper(bearer[0:6]) == "BEARER" {
  34. tokenStr = bearer[7:]
  35. }
  36. }
  37. // Get token from cookie
  38. if tokenStr == "" {
  39. cookie, err := r.Cookie("jwt")
  40. if err == nil {
  41. tokenStr = cookie.Value
  42. }
  43. }
  44. return EncodedJwt(tokenStr)
  45. }
  46. func EncodeJwt(secret Secret, claims *jwt.StandardClaims) (EncodedJwt, error) {
  47. if secret == "" {
  48. return "", nil
  49. }
  50. t := jwt.New(jwt.GetSigningMethod("HS256"))
  51. t.Claims = claims
  52. encoded, e := t.SignedString(secret)
  53. return EncodedJwt(encoded), e
  54. }
  55. func DecodeJwt(secret Secret, tokenString EncodedJwt) (token *jwt.Token, err error) {
  56. // check exp, nbf
  57. return jwt.Parse(string(tokenString), func(token *jwt.Token) (interface{}, error) {
  58. return secret, nil
  59. })
  60. }