This repository has been archived by the owner on Apr 28, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.go
79 lines (70 loc) · 2.08 KB
/
middleware.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
package auth
import (
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/txsvc/service/pkg/jwt"
"github.com/txsvc/service/pkg/svc"
)
type (
// Client represents the claim of the client calling the API
Client struct {
ClientID string `json:"client_id"`
UserID string `json:"user_id"`
Scope string `json:"scope"`
}
)
const (
identityKey = "client_id"
)
// GetSecureJWTMiddleware instantiates a JWT middleware and all the necessary handlers
func GetSecureJWTMiddleware(realm, secretKey string) (*jwt.GinJWTMiddleware, error) {
return jwt.New(&jwt.GinJWTMiddleware{
Realm: realm,
Key: []byte(secretKey),
//Timeout: timeout,
//MaxRefresh: maxRefresh,
IdentityKey: identityKey,
PayloadFunc: PayloadMappingHandler,
IdentityHandler: IdentityHandler,
Authenticator: nil, // none provided as we do not have a 'login' function for API clients
Authorizator: ScopeAuthorizationHandler,
//Unauthorized: Unauthorized,
TokenLookup: "header: Authorization, query: token, cookie: jwt",
TokenHeadName: "Bearer",
TimeFunc: time.Now,
})
}
// PayloadMappingHandler extracts the client_id, user_id and scope of the request
func PayloadMappingHandler(data interface{}) jwt.MapClaims {
if v, ok := data.(*Client); ok {
return jwt.MapClaims{
"client_id": v.ClientID,
"user_id": v.UserID,
"scope": v.Scope,
}
}
return jwt.MapClaims{}
}
// IdentityHandler returns the Client structure
func IdentityHandler(c *gin.Context) interface{} {
claims := jwt.ExtractClaims(c)
if claims[identityKey] == "" {
// FIXME: see Issue #170, check if identityKey exists in claims
return nil
}
return &Client{
ClientID: claims[identityKey].(string),
UserID: claims["user_id"].(string),
Scope: claims["scope"].(string),
}
}
// ScopeAuthorizationHandler checks for required scopes
func ScopeAuthorizationHandler(data interface{}, c *gin.Context) bool {
// FIXME: this is a very simple and naive implementation !
if v, ok := data.(*Client); ok {
rr := svc.GetRequiredScopes(c)
return strings.Contains(v.Scope, rr)
}
return false
}