jwt.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package security
  2. import (
  3. "bytes"
  4. "fmt"
  5. "net/http"
  6. "strings"
  7. "time"
  8. "github.com/dgrijalva/jwt-go"
  9. "github.com/valyala/fasthttp"
  10. "github.com/chrislusf/seaweedfs/weed/glog"
  11. )
  12. type EncodedJwt string
  13. type SigningKey []byte
  14. type SeaweedFileIdClaims struct {
  15. Fid string `json:"fid"`
  16. jwt.StandardClaims
  17. }
  18. func GenJwt(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 OldGetJwt(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 GetJwt(ctx *fasthttp.RequestCtx) EncodedJwt {
  50. // Get token from query params
  51. tokenStr := ctx.FormValue("jwt")
  52. // Get token from authorization header
  53. if tokenStr == nil {
  54. bearer := ctx.Request.Header.Peek("Authorization")
  55. if len(bearer) > 7 && string(bytes.ToUpper(bearer[0:6])) == "BEARER" {
  56. tokenStr = bearer[7:]
  57. }
  58. }
  59. return EncodedJwt(tokenStr)
  60. }
  61. func DecodeJwt(signingKey SigningKey, tokenString EncodedJwt) (token *jwt.Token, err error) {
  62. // check exp, nbf
  63. return jwt.ParseWithClaims(string(tokenString), &SeaweedFileIdClaims{}, func(token *jwt.Token) (interface{}, error) {
  64. if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
  65. return nil, fmt.Errorf("unknown token method")
  66. }
  67. return []byte(signingKey), nil
  68. })
  69. }