-
Notifications
You must be signed in to change notification settings - Fork 1
/
jwt.go
51 lines (43 loc) · 898 Bytes
/
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
package middleware
import (
"github.com/go-zoox/jwt"
"github.com/go-zoox/zoox"
)
// Jwt is a middleware that authenticates via JWT.
func Jwt(secret string, algorithm ...string) zoox.Middleware {
algorithmX := "HS256"
if len(algorithm) > 0 {
algorithmX = algorithm[0]
}
var j *jwt.Jwt
switch algorithmX {
case "HS256":
j = jwt.NewHS256(secret)
case "HS384":
j = jwt.NewHS384(secret)
case "HS512":
j = jwt.NewHS512(secret)
default:
panic("unknown algorithm, allowed: HS256, HS384, HS512")
}
return func(ctx *zoox.Context) {
authHeader := ctx.Get("Authorization")
if authHeader == "" {
authHeader = ctx.Query().Get("access_token")
}
if authHeader == "" {
ctx.Status(401)
return
}
token := authHeader[7:]
if token == "" {
ctx.Status(401)
return
}
if err := j.Verify(token); err != nil {
ctx.Status(401)
return
}
ctx.Next()
}
}