MCPcopy
hub / github.com/micro/go-micro / AuthHandler

Function AuthHandler

wrapper/auth/server.go:44–110  ·  view source on GitHub ↗

AuthHandler returns a server HandlerWrapper that enforces authentication and authorization. For each incoming request: 1. Extracts Bearer token from metadata 2. Verifies token using auth.Inspect() 3. Checks authorization using rules.Verify() 4. Adds account to context 5. Calls the handler if author

(opts HandlerOptions)

Source from the content-addressed store, hash-verified

42// })),
43// )
44func AuthHandler(opts HandlerOptions) server.HandlerWrapper {
45 return func(h server.HandlerFunc) server.HandlerFunc {
46 return func(ctx context.Context, req server.Request, rsp interface{}) error {
47 // Get endpoint name
48 endpoint := req.Endpoint()
49
50 // Check if this endpoint should skip auth
51 for _, skip := range opts.SkipEndpoints {
52 if skip == endpoint {
53 // Skip auth, proceed to handler
54 return h(ctx, req, rsp)
55 }
56 }
57
58 // Extract metadata from context
59 md, ok := metadata.FromContext(ctx)
60 if !ok {
61 return errors.Unauthorized(req.Service(), "missing metadata")
62 }
63
64 // Extract and verify token
65 token, err := TokenFromMetadata(md)
66 if err != nil {
67 if err == ErrMissingToken {
68 return errors.Unauthorized(req.Service(), "missing authorization token")
69 }
70 return errors.Unauthorized(req.Service(), "invalid authorization token: %v", err)
71 }
72
73 // Verify token and get account
74 var account *auth.Account
75 if opts.Auth != nil {
76 account, err = opts.Auth.Inspect(token)
77 if err != nil {
78 if err == auth.ErrInvalidToken {
79 return errors.Unauthorized(req.Service(), "invalid token")
80 }
81 return errors.Unauthorized(req.Service(), "token verification failed: %v", err)
82 }
83 }
84
85 // Check authorization if rules are provided
86 if opts.Rules != nil && account != nil {
87 resource := &auth.Resource{
88 Name: req.Service(),
89 Type: "service",
90 Endpoint: endpoint,
91 }
92
93 if err := opts.Rules.Verify(account, resource); err != nil {
94 if err == auth.ErrForbidden {
95 return errors.Forbidden(req.Service(), "access denied to %s", endpoint)
96 }
97 return errors.Forbidden(req.Service(), "authorization failed: %v", err)
98 }
99 }
100
101 // Add account to context for handler to use

Callers

nothing calls this directly

Calls 9

FromContextFunction · 0.92
UnauthorizedFunction · 0.92
ForbiddenFunction · 0.92
ContextWithAccountFunction · 0.92
TokenFromMetadataFunction · 0.85
EndpointMethod · 0.65
ServiceMethod · 0.65
InspectMethod · 0.65
VerifyMethod · 0.65

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…