aboutsummaryrefslogtreecommitdiff
path: root/weed/security/jwt.go
blob: c6da5c7aa2eb1b62306fc4727a8582c7b2b207fb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package security

import (
	"bytes"
	"fmt"
	"net/http"
	"strings"
	"time"

	"github.com/dgrijalva/jwt-go"
	"github.com/valyala/fasthttp"

	"github.com/chrislusf/seaweedfs/weed/glog"
)

type EncodedJwt string
type SigningKey []byte

type SeaweedFileIdClaims struct {
	Fid string `json:"fid"`
	jwt.StandardClaims
}

func GenJwt(signingKey SigningKey, expiresAfterSec int, fileId string) EncodedJwt {
	if len(signingKey) == 0 {
		return ""
	}

	claims := SeaweedFileIdClaims{
		fileId,
		jwt.StandardClaims{},
	}
	if expiresAfterSec > 0 {
		claims.ExpiresAt = time.Now().Add(time.Second * time.Duration(expiresAfterSec)).Unix()
	}
	t := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	encoded, e := t.SignedString([]byte(signingKey))
	if e != nil {
		glog.V(0).Infof("Failed to sign claims %+v: %v", t.Claims, e)
		return ""
	}
	return EncodedJwt(encoded)
}

func OldGetJwt(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)
}

func GetJwt(ctx *fasthttp.RequestCtx) EncodedJwt {

	// Get token from query params
	tokenStr := ctx.FormValue("jwt")

	// Get token from authorization header
	if tokenStr == nil {
		bearer := ctx.Request.Header.Peek("Authorization")
		if len(bearer) > 7 && string(bytes.ToUpper(bearer[0:6])) == "BEARER" {
			tokenStr = bearer[7:]
		}
	}

	return EncodedJwt(tokenStr)
}

func DecodeJwt(signingKey SigningKey, tokenString EncodedJwt) (token *jwt.Token, err error) {
	// check exp, nbf
	return jwt.ParseWithClaims(string(tokenString), &SeaweedFileIdClaims{}, func(token *jwt.Token) (interface{}, error) {
		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, fmt.Errorf("unknown token method")
		}
		return []byte(signingKey), nil
	})
}