2015-02-08 07:35:28 +08:00
|
|
|
package security
|
|
|
|
|
|
|
|
import (
|
2019-02-14 16:08:20 +08:00
|
|
|
"fmt"
|
2015-02-08 07:35:28 +08:00
|
|
|
"net/http"
|
|
|
|
"strings"
|
|
|
|
"time"
|
|
|
|
|
2016-06-03 09:09:14 +08:00
|
|
|
"github.com/chrislusf/seaweedfs/weed/glog"
|
2021-07-23 01:22:09 +08:00
|
|
|
"github.com/golang-jwt/jwt"
|
2015-02-08 07:35:28 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
type EncodedJwt string
|
2019-02-14 16:08:20 +08:00
|
|
|
type SigningKey []byte
|
|
|
|
|
|
|
|
type SeaweedFileIdClaims struct {
|
|
|
|
Fid string `json:"fid"`
|
|
|
|
jwt.StandardClaims
|
|
|
|
}
|
2015-02-08 07:35:28 +08:00
|
|
|
|
2019-05-04 23:42:25 +08:00
|
|
|
func GenJwt(signingKey SigningKey, expiresAfterSec int, fileId string) EncodedJwt {
|
2019-02-14 16:08:20 +08:00
|
|
|
if len(signingKey) == 0 {
|
2015-02-08 07:35:28 +08:00
|
|
|
return ""
|
|
|
|
}
|
|
|
|
|
2019-02-14 16:08:20 +08:00
|
|
|
claims := SeaweedFileIdClaims{
|
|
|
|
fileId,
|
2019-05-04 23:42:25 +08:00
|
|
|
jwt.StandardClaims{},
|
|
|
|
}
|
|
|
|
if expiresAfterSec > 0 {
|
|
|
|
claims.ExpiresAt = time.Now().Add(time.Second * time.Duration(expiresAfterSec)).Unix()
|
2016-06-19 09:57:33 +08:00
|
|
|
}
|
2019-02-14 16:08:20 +08:00
|
|
|
t := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
|
|
|
encoded, e := t.SignedString([]byte(signingKey))
|
2015-02-08 07:35:28 +08:00
|
|
|
if e != nil {
|
2019-02-14 16:08:20 +08:00
|
|
|
glog.V(0).Infof("Failed to sign claims %+v: %v", t.Claims, e)
|
2015-02-08 07:35:28 +08:00
|
|
|
return ""
|
|
|
|
}
|
|
|
|
return EncodedJwt(encoded)
|
|
|
|
}
|
|
|
|
|
|
|
|
func GetJwt(r *http.Request) EncodedJwt {
|
|
|
|
|
|
|
|
// Get token from query params
|
|
|
|
tokenStr := r.URL.Query().Get("jwt")
|
|
|
|
|
|
|
|
// Get token from authorization header
|
|
|
|
if tokenStr == "" {
|
|
|
|
bearer := r.Header.Get("Authorization")
|
|
|
|
if len(bearer) > 7 && strings.ToUpper(bearer[0:6]) == "BEARER" {
|
|
|
|
tokenStr = bearer[7:]
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return EncodedJwt(tokenStr)
|
|
|
|
}
|
|
|
|
|
2019-02-10 13:56:32 +08:00
|
|
|
func DecodeJwt(signingKey SigningKey, tokenString EncodedJwt) (token *jwt.Token, err error) {
|
2015-02-08 07:35:28 +08:00
|
|
|
// check exp, nbf
|
2019-02-15 16:09:19 +08:00
|
|
|
return jwt.ParseWithClaims(string(tokenString), &SeaweedFileIdClaims{}, func(token *jwt.Token) (interface{}, error) {
|
2019-02-14 16:08:20 +08:00
|
|
|
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
|
|
|
return nil, fmt.Errorf("unknown token method")
|
|
|
|
}
|
2019-02-15 16:09:19 +08:00
|
|
|
return []byte(signingKey), nil
|
2015-02-08 07:35:28 +08:00
|
|
|
})
|
|
|
|
}
|