-
-
Notifications
You must be signed in to change notification settings - Fork 27
/
auth.go
193 lines (163 loc) · 4.42 KB
/
auth.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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
package auth
import (
"crypto/rsa"
"net/http"
"strings"
"github.com/casbin/casbin/v2"
"github.com/casbin/casbin/v2/persist"
"github.com/dgrijalva/jwt-go"
"github.com/dgrijalva/jwt-go/request"
"github.com/dgrijalva/jwt-go/test"
"github.com/micro/cli"
"github.com/micro/go-micro/errors"
"github.com/micro/go-micro/util/log"
"github.com/micro-in-cn/x-gateway/plugin"
)
const id = "micro.x-gateway.auth"
var adapters map[string]persist.Adapter
var watchers map[string]persist.Watcher
func init() {
adapters = make(map[string]persist.Adapter)
watchers = make(map[string]persist.Watcher)
}
//RegisterAdapter of auth
func RegisterAdapter(key string, a persist.Adapter) {
adapters[key] = a
}
//RegisterWatcher of auth
func RegisterWatcher(key string, w persist.Watcher) {
watchers[key] = w
}
//Auth for micro
type Auth struct {
options Options
enforcer *casbin.Enforcer
pubUser string
pubKey *rsa.PublicKey
}
func (a *Auth) keyFunc(*jwt.Token) (interface{}, error) {
return a.pubKey, nil
}
func (a *Auth) handler(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if a.options.skipperFunc(r) {
h.ServeHTTP(w, r)
return
}
path := r.URL.Path
method := r.Method
// Public接口
if a.pubUser != "" {
allowed, err := a.enforcer.Enforce(a.pubUser, path, method)
if err != nil {
a.options.responseHandler(w, r, errors.InternalServerError(id, err.Error()))
return
} else if allowed {
h.ServeHTTP(w, r)
return
}
}
// JWT token验证
token, err := request.ParseFromRequest(
r,
request.AuthorizationHeaderExtractor,
a.keyFunc,
request.WithClaims(&jwt.StandardClaims{}),
)
if err != nil || token == nil {
a.options.responseHandler(w, r, errors.Unauthorized(id, "JWT token parse token=nil or with error: %v", err.Error()))
return
}
if !token.Valid {
a.options.responseHandler(w, r, errors.Unauthorized(id, "JWT token invalid"))
return
}
// 访问控制
claims := token.Claims.(*jwt.StandardClaims)
if allowed, err := a.enforcer.Enforce(claims.Id, path, method); err != nil {
a.options.responseHandler(w, r, errors.InternalServerError(id, err.Error()))
return
} else if !allowed {
log.Infof("Claims ID: %v, path: %v, method: %v", claims.Id, path, method)
a.options.responseHandler(w, r, errors.Forbidden(id, "Casbin access control not allowed"))
return
}
// 将用户ID加入Header
r.Header.Set("UserId", claims.Id)
// otherwise serve everything
h.ServeHTTP(w, r)
})
}
//NewPlugin for auth
func NewPlugin(opts ...Option) plugin.Plugin {
options := newOptions(opts...)
a := &Auth{
options: options,
}
var egAdapter, egWatcher []string
for k := range adapters {
egAdapter = append(egAdapter, k)
}
for k := range watchers {
egWatcher = append(egWatcher, k)
}
return plugin.NewPlugin(
plugin.WithName("Auth"),
plugin.WithFlag(
cli.StringFlag{
Name: "auth_pub_key",
Usage: "Auth public key file",
Value: "./conf/auth_key.pub",
},
cli.StringFlag{
Name: "casbin_model",
Usage: "Casbin model config file",
Value: "./conf/casbin_model.conf",
},
cli.StringFlag{
Name: "casbin_adapter",
Usage: "Casbin registed adapter {" + strings.Join(egAdapter, ", ") + "}",
Value: "default",
},
cli.StringFlag{
Name: "casbin_watcher",
Usage: "Casbin registed watcher {" + strings.Join(egWatcher, ", ") + "}",
Value: "default",
},
cli.StringFlag{
Name: "casbin_public_user",
Usage: "Casbin public user",
Value: "public",
},
),
plugin.WithHandler(a.handler),
plugin.WithInit(func(ctx *cli.Context) error {
a.pubUser = ctx.String("casbin_public_user")
pubKey := ctx.String("auth_pub_key")
a.pubKey = test.LoadRSAPublicKeyFromDisk(pubKey)
model := ctx.String("casbin_model")
adapter := ctx.String("casbin_adapter")
watcher := ctx.String("casbin_watcher")
var e *casbin.Enforcer
if a, ok := adapters[adapter]; ok {
var err error
e, err = casbin.NewEnforcer(model, a)
if err != nil {
return err
}
} else {
return errors.New(id, "adapter not exist", http.StatusInternalServerError)
}
// Load the policy.
e.LoadPolicy()
// Set the watcher for the enforcer.
if w, ok := watchers[watcher]; ok {
e.SetWatcher(w)
// Set callback to local example
// c.watcher.SetUpdateCallback(func(string) { e.LoadPolicy() })
}
a.enforcer = e
return nil
}),
)
}