This repository has been archived by the owner on Jul 4, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathauth.go
77 lines (64 loc) · 1.74 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
package main
import (
"context"
"errors"
"strings"
"go-micro.dev/v4"
"go-micro.dev/v4/auth"
"go-micro.dev/v4/metadata"
"go-micro.dev/v4/server"
)
var (
catchallResource = &auth.Resource{
Type: "*",
Name: "*",
Endpoint: "*",
}
callResource = &auth.Resource{
Type: "service",
Name: "my.service.name",
Endpoint: "Helloworld.MyMethod",
}
// Rules to validate against
rules = []*auth.Rule{
// Enforce auth on all endpoints.
{Scope: "*", Resource: catchallResource},
// Enforce auth on one specific endpoint.
{Scope: "*", Resource: callResource},
}
)
func NewAuthWrapper(service micro.Service) server.HandlerWrapper {
return func(h server.HandlerFunc) server.HandlerFunc {
return func(ctx context.Context, req server.Request, rsp interface{}) error {
// Fetch metadata from context (request headers).
md, b := metadata.FromContext(ctx)
if !b {
return errors.New("no metadata found")
}
// Get auth header.
authHeader, ok := md["Authorization"]
if !ok || !strings.HasPrefix(authHeader, auth.BearerScheme) {
return errors.New("no auth token provided")
}
// Extract auth token.
token := strings.TrimPrefix(authHeader, auth.BearerScheme)
// Extract account from token.
a := service.Options().Auth
acc, err := a.Inspect(token)
if err != nil {
return errors.New("auth token invalid")
}
// Create resource for current endpoint from request headers.
currentResource := auth.Resource{
Type: "service",
Name: md["Micro-Service"],
Endpoint: md["Micro-Endpoint"],
}
// Verify if account has access.
if err := auth.Verify(rules, acc, ¤tResource); err != nil {
return errors.New("no access")
}
return h(ctx, req, rsp)
}
}
}