This repository has been archived by the owner on Mar 21, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
jwt.go
114 lines (93 loc) · 2.19 KB
/
jwt.go
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
package jwt
import (
"fmt"
"time"
"github.com/dgrijalva/jwt-go"
"github.com/lunny/tango"
)
var (
Bearer = "Bearer"
DefaultKey = "JWT"
)
type auther interface {
SetClaims(map[string]interface{})
GetClaim(string) interface{}
}
type Auther map[string]interface{}
func (a Auther) SetClaims(claims map[string]interface{}) {
a = claims
}
func (a Auther) GetClaim(key string) interface{} {
return a[key]
}
type Options struct {
KeyFunc func(*tango.Context) (string, error)
CheckWebSocket bool
}
func prepareOptions(opts []Options) Options {
var opt Options
if len(opts) > 0 {
opt = opts[0]
}
if opt.KeyFunc == nil {
opt.KeyFunc = func(ctx *tango.Context) (string, error) {
return DefaultKey, nil
}
}
return opt
}
// A JSON Web Token middleware
func New(opts ...Options) tango.HandlerFunc {
opt := prepareOptions(opts)
return func(ctx *tango.Context) {
if !opt.CheckWebSocket {
// Skip WebSocket
if (ctx.Req().Header.Get("Upgrade")) == "WebSocket" {
ctx.Next()
return
}
}
if a, ok := ctx.Action().(auther); ok {
key, err := opt.KeyFunc(ctx)
if err != nil {
ctx.Result = err
return
}
auth := ctx.Req().Header.Get("Authorization")
l := len(Bearer)
if len(auth) > l+1 && auth[:l] == Bearer {
t, err := jwt.Parse(auth[l+1:], func(token *jwt.Token) (interface{}, error) {
// Always check the signing method
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
}
// Return the key for validation
return []byte(key), nil
})
if err == nil && t.Valid {
// Store token claims
a.SetClaims(t.Claims)
ctx.Next()
return
}
}
ctx.Result = tango.Unauthorized()
return
}
ctx.Next()
}
}
func NewToken(key string, claims ...map[string]interface{}) (string, error) {
// New web token.
token := jwt.New(jwt.SigningMethodHS256)
// Set a header and a claim
token.Header["typ"] = "JWT"
token.Claims["exp"] = time.Now().Add(time.Second * 60).Unix()
if len(claims) > 0 {
for k, v := range claims[0] {
token.Claims[k] = v
}
}
// Generate encoded token
return token.SignedString([]byte(key))
}