-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconditional_auth.go
More file actions
168 lines (148 loc) · 5.13 KB
/
conditional_auth.go
File metadata and controls
168 lines (148 loc) · 5.13 KB
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
package fiberoapi
import (
"errors"
"strings"
"github.com/gofiber/fiber/v2"
)
// ConditionalAuthMiddleware creates middleware that applies only to specified routes
func ConditionalAuthMiddleware(authMiddleware fiber.Handler, excludePaths ...string) fiber.Handler {
return func(c *fiber.Ctx) error {
path := c.Path()
// Verify if the current path is in the exclude list
for _, excludePath := range excludePaths {
if excludePath != "" && (path == excludePath || strings.HasPrefix(path, excludePath)) {
return c.Next() // Skip authentication
}
}
// Apply authentication middleware
return authMiddleware(c)
}
}
// SmartAuthMiddleware creates middleware that automatically excludes documentation routes.
// When SecuritySchemes are configured, it uses MultiSchemeAuthMiddleware for dispatch.
// Otherwise, it falls back to BearerTokenMiddleware for backward compatibility.
func SmartAuthMiddleware(authService AuthorizationService, config Config) fiber.Handler {
var authMiddleware fiber.Handler
if len(config.SecuritySchemes) > 0 {
authMiddleware = MultiSchemeAuthMiddleware(authService, config)
} else {
authMiddleware = BearerTokenMiddleware(authService)
}
// Paths to exclude from authentication
excludePaths := []string{
config.OpenAPIDocsPath, // /docs
config.OpenAPIJSONPath, // /openapi.json
config.OpenAPIYamlPath, // /openapi.yaml
}
return ConditionalAuthMiddleware(authMiddleware, excludePaths...)
}
// MultiSchemeAuthMiddleware creates middleware that tries configured security schemes.
// It iterates over DefaultSecurity requirements (OR semantics) and validates
// using the appropriate scheme handler.
func MultiSchemeAuthMiddleware(authService AuthorizationService, config Config) fiber.Handler {
return func(c *fiber.Ctx) error {
securityReqs := config.DefaultSecurity
if len(securityReqs) == 0 {
securityReqs = buildDefaultFromSchemes(config.SecuritySchemes)
}
// Server configuration errors (5xx) short-circuit immediately since
// no alternative requirement can fix a misconfigured scheme.
var lastErr error
for _, requirement := range securityReqs {
authCtx, err := validateSecurityRequirement(c, requirement, config.SecuritySchemes, authService)
if err == nil {
c.Locals("auth", authCtx)
return c.Next()
}
var authErr *AuthError
if errors.As(err, &authErr) && authErr.StatusCode >= 500 {
return c.Status(authErr.StatusCode).JSON(fiber.Map{
"error": "Server configuration error",
"details": authErr.Message,
})
}
lastErr = err
}
if lastErr == nil {
// No security requirements were configured — this is a server misconfiguration,
// not a client authentication failure.
return c.Status(500).JSON(fiber.Map{
"error": "Server configuration error",
"details": "no security schemes configured",
})
}
status := 401
errorLabel := "Authentication failed"
var scopeErr *ScopeError
if errors.As(lastErr, &scopeErr) {
status = 403
errorLabel = "Authorization failed"
}
return c.Status(status).JSON(fiber.Map{
"error": errorLabel,
"details": lastErr.Error(),
})
}
}
// BasicAuthMiddleware creates a standalone middleware for HTTP Basic authentication.
// The authService must implement the BasicAuthValidator interface.
func BasicAuthMiddleware(validator AuthorizationService) fiber.Handler {
return func(c *fiber.Ctx) error {
authCtx, err := validateBasicAuth(c, validator)
if err != nil {
status, label := classifyAuthError(err)
return c.Status(status).JSON(fiber.Map{
"error": label,
"details": err.Error(),
})
}
c.Locals("auth", authCtx)
return c.Next()
}
}
// APIKeyMiddleware creates a standalone middleware for API Key authentication.
// The authService must implement the APIKeyValidator interface.
func APIKeyMiddleware(validator AuthorizationService, scheme SecurityScheme) fiber.Handler {
return func(c *fiber.Ctx) error {
authCtx, err := validateAPIKey(c, scheme, validator)
if err != nil {
status, label := classifyAuthError(err)
return c.Status(status).JSON(fiber.Map{
"error": label,
"details": err.Error(),
})
}
c.Locals("auth", authCtx)
return c.Next()
}
}
// AWSSignatureMiddleware creates a standalone middleware for AWS Signature V4 authentication.
// The authService must implement the AWSSignatureValidator interface.
func AWSSignatureMiddleware(validator AuthorizationService) fiber.Handler {
return func(c *fiber.Ctx) error {
authCtx, err := validateAWSSigV4(c, validator)
if err != nil {
status, label := classifyAuthError(err)
return c.Status(status).JSON(fiber.Map{
"error": label,
"details": err.Error(),
})
}
c.Locals("auth", authCtx)
return c.Next()
}
}
// classifyAuthError returns the HTTP status and error label for an authentication error.
func classifyAuthError(err error) (int, string) {
var authErr *AuthError
if errors.As(err, &authErr) {
if authErr.StatusCode >= 500 {
return authErr.StatusCode, "Server configuration error"
}
if authErr.StatusCode == 403 {
return authErr.StatusCode, "Authorization failed"
}
return authErr.StatusCode, "Authentication failed"
}
return 401, "Authentication failed"
}