Skip to content

Commit ceacde5

Browse files
authored
🧹 chore: Remove support for PasswordFromContext from BasicAuth middleware (#3638)
1 parent e8345f9 commit ceacde5

File tree

5 files changed

+14
-75
lines changed

5 files changed

+14
-75
lines changed

docs/middleware/basicauth.md

Lines changed: 1 addition & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -6,14 +6,13 @@ id: basicauth
66

77
Basic Authentication middleware for [Fiber](https://github.com/gofiber/fiber) that provides an HTTP basic authentication. It calls the next handler for valid credentials and [401 Unauthorized](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/401) or a custom response for missing or invalid credentials.
88

9-
The default unauthorized response includes the header `WWW-Authenticate: Basic realm="Restricted", charset="UTF-8"` and sets `Cache-Control: no-store`.
9+
The default unauthorized response includes the header `WWW-Authenticate: Basic realm="Restricted", charset="UTF-8"`, sets `Cache-Control: no-store`, and adds a `Vary: Authorization` header.
1010

1111
## Signatures
1212

1313
```go
1414
func New(config Config) fiber.Handler
1515
func UsernameFromContext(c fiber.Ctx) string
16-
func PasswordFromContext(c fiber.Ctx) string
1716
```
1817

1918
## Examples
@@ -72,15 +71,6 @@ hashing algorithm from a prefix:
7271
If no prefix is present the value is interpreted as a SHA-256 digest encoded in
7372
hex or base64. Plaintext passwords are rejected.
7473

75-
```go
76-
func handler(c fiber.Ctx) error {
77-
username := basicauth.UsernameFromContext(c)
78-
password := basicauth.PasswordFromContext(c)
79-
log.Printf("Username: %s Password: %s", username, password)
80-
return c.SendString("Hello, " + username)
81-
}
82-
```
83-
8474
## Config
8575

8676
| Property | Type | Description | Default |
@@ -90,7 +80,6 @@ func handler(c fiber.Ctx) error {
9080
| Realm | `string` | Realm is a string to define the realm attribute of BasicAuth. The realm identifies the system to authenticate against and can be used by clients to save credentials. | `"Restricted"` |
9181
| Charset | `string` | Charset sent in the `WWW-Authenticate` header, so clients know how credentials are encoded. | `"UTF-8"` |
9282
| HeaderLimit | `int` | Maximum allowed length of the `Authorization` header. Requests exceeding this limit are rejected. | `8192` |
93-
| StorePassword | `bool` | Store the plaintext password in the context and retrieve it via `PasswordFromContext`. | `false` |
9483
| Authorizer | `func(string, string, fiber.Ctx) bool` | Authorizer defines a function to check the credentials. It will be called with a username, password, and the current context and is expected to return true or false to indicate approval. | `nil` |
9584
| Unauthorized | `fiber.Handler` | Unauthorized defines the response body for unauthorized responses. | `nil` |
9685

@@ -103,7 +92,6 @@ var ConfigDefault = Config{
10392
Realm: "Restricted",
10493
Charset: "UTF-8",
10594
HeaderLimit: 8192,
106-
StorePassword: false,
10795
Authorizer: nil,
10896
Unauthorized: nil,
10997
}

docs/whats_new.md

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1019,7 +1019,6 @@ Examples include:
10191019
- `csrf.HandlerFromContext(c)`
10201020
- `session.FromContext(c)`
10211021
- `basicauth.UsernameFromContext(c)`
1022-
- `basicauth.PasswordFromContext(c)`
10231022
- `keyauth.TokenFromContext(c)`
10241023

10251024
When used with the Logger middleware, the recommended approach is to use the `CustomTags` feature of the logger, which allows you to call these specific `FromContext` functions. See the [Logger](#logger) section for more details.
@@ -1054,7 +1053,7 @@ The adaptor middleware has been significantly optimized for performance and effi
10541053

10551054
### BasicAuth
10561055

1057-
The BasicAuth middleware now validates the `Authorization` header more rigorously and sets security-focused response headers. Passwords must be provided in **hashed** form (e.g. SHA-256 or bcrypt) rather than plaintext. The default challenge includes the `charset="UTF-8"` parameter and disables caching. Passwords are no longer stored in the request context by default; use the new `StorePassword` option to retain them. A `Charset` option controls the value used in the challenge header.
1056+
The BasicAuth middleware now validates the `Authorization` header more rigorously and sets security-focused response headers. Passwords must be provided in **hashed** form (e.g. SHA-256 or bcrypt) rather than plaintext. The default challenge includes the `charset="UTF-8"` parameter and disables caching. Responses also set a `Vary: Authorization` header to prevent caching based on credentials. Passwords are no longer stored in the request context. A `Charset` option controls the value used in the challenge header.
10581057
A new `HeaderLimit` option restricts the maximum length of the `Authorization` header (default: `8192` bytes).
10591058
The `Authorizer` function now receives the current `fiber.Ctx` as a third argument, allowing credential checks to incorporate request context.
10601059

@@ -1916,7 +1915,6 @@ You must update your code to use the dedicated exported functions provided by ea
19161915
- `csrf.HandlerFromContext(c)`
19171916
- `session.FromContext(c)`
19181917
- `basicauth.UsernameFromContext(c)`
1919-
- `basicauth.PasswordFromContext(c)`
19201918
- `keyauth.TokenFromContext(c)`
19211919

19221920
**For logging these values:**
@@ -1947,9 +1945,9 @@ Authorizer: func(user, pass string, _ fiber.Ctx) bool {
19471945
}
19481946
```
19491947
1950-
Passwords configured for BasicAuth must now be pre-hashed. If no prefix is supplied the middleware expects a SHA-256 digest encoded in hex. Common prefixes like `{SHA256}` and `{SHA512}` and bcrypt strings are also supported. Plaintext passwords are no longer accepted.
1948+
Passwords configured for BasicAuth must now be pre-hashed. If no prefix is supplied the middleware expects a SHA-256 digest encoded in hex. Common prefixes like `{SHA256}` and `{SHA512}` and bcrypt strings are also supported. Plaintext passwords are no longer accepted. Unauthorized responses also include a `Vary: Authorization` header for correct caching behavior.
19511949
1952-
You can also set the optional `HeaderLimit`, `StorePassword`, and `Charset`
1950+
You can also set the optional `HeaderLimit` and `Charset`
19531951
options to further control authentication behavior.
19541952
19551953
#### Cache

middleware/basicauth/basicauth.go

Lines changed: 1 addition & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -12,10 +12,9 @@ import (
1212
// other packages.
1313
type contextKey int
1414

15-
// The keys for the values in context
15+
// The key for the username value stored in the context
1616
const (
1717
usernameKey contextKey = iota
18-
passwordKey
1918
)
2019

2120
const basicScheme = "Basic"
@@ -70,9 +69,6 @@ func New(config Config) fiber.Handler {
7069

7170
if cfg.Authorizer(username, password, c) {
7271
c.Locals(usernameKey, username)
73-
if cfg.StorePassword {
74-
c.Locals(passwordKey, password)
75-
}
7672
return c.Next()
7773
}
7874

@@ -90,13 +86,3 @@ func UsernameFromContext(c fiber.Ctx) string {
9086
}
9187
return username
9288
}
93-
94-
// PasswordFromContext returns the password found in the context
95-
// returns an empty string if the password does not exist
96-
func PasswordFromContext(c fiber.Ctx) string {
97-
password, ok := c.Locals(passwordKey).(string)
98-
if !ok {
99-
return ""
100-
}
101-
return password
102-
}

middleware/basicauth/basicauth_test.go

Lines changed: 2 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -54,14 +54,11 @@ func Test_Middleware_BasicAuth(t *testing.T) {
5454
"john": hashedJohn,
5555
"admin": string(hashedAdmin),
5656
},
57-
StorePassword: true,
5857
}))
5958

6059
app.Get("/testauth", func(c fiber.Ctx) error {
6160
username := UsernameFromContext(c)
62-
password := PasswordFromContext(c)
63-
64-
return c.SendString(username + password)
61+
return c.SendString(username)
6562
})
6663

6764
tests := []struct {
@@ -105,34 +102,11 @@ func Test_Middleware_BasicAuth(t *testing.T) {
105102
require.Equal(t, tt.statusCode, resp.StatusCode)
106103

107104
if tt.statusCode == 200 {
108-
require.Equal(t, fmt.Sprintf("%s%s", tt.username, tt.password), string(body))
105+
require.Equal(t, tt.username, string(body))
109106
}
110107
}
111108
}
112109

113-
func Test_BasicAuth_NoStorePassword(t *testing.T) {
114-
t.Parallel()
115-
app := fiber.New()
116-
117-
hashedJohn := sha256Hash("doe")
118-
119-
app.Use(New(Config{
120-
Users: map[string]string{"john": hashedJohn},
121-
}))
122-
123-
app.Get("/", func(c fiber.Ctx) error {
124-
require.Empty(t, PasswordFromContext(c))
125-
return c.SendStatus(fiber.StatusOK)
126-
})
127-
128-
creds := base64.StdEncoding.EncodeToString([]byte("john:doe"))
129-
req := httptest.NewRequest(fiber.MethodGet, "/", nil)
130-
req.Header.Set(fiber.HeaderAuthorization, "Basic "+creds)
131-
resp, err := app.Test(req)
132-
require.NoError(t, err)
133-
require.Equal(t, fiber.StatusOK, resp.StatusCode)
134-
}
135-
136110
func Test_BasicAuth_AuthorizerCtx(t *testing.T) {
137111
t.Parallel()
138112
app := fiber.New()

middleware/basicauth/config.go

Lines changed: 7 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -63,24 +63,17 @@ type Config struct {
6363
//
6464
// Optional. Default: 8192.
6565
HeaderLimit int
66-
67-
// StorePassword determines if the plaintext password should be stored
68-
// in the context for later retrieval via PasswordFromContext.
69-
//
70-
// Optional. Default: false.
71-
StorePassword bool
7266
}
7367

7468
// ConfigDefault is the default config
7569
var ConfigDefault = Config{
76-
Next: nil,
77-
Users: map[string]string{},
78-
Realm: "Restricted",
79-
Charset: "UTF-8",
80-
HeaderLimit: 8192,
81-
StorePassword: false,
82-
Authorizer: nil,
83-
Unauthorized: nil,
70+
Next: nil,
71+
Users: map[string]string{},
72+
Realm: "Restricted",
73+
Charset: "UTF-8",
74+
HeaderLimit: 8192,
75+
Authorizer: nil,
76+
Unauthorized: nil,
8477
}
8578

8679
// Helper function to set default values

0 commit comments

Comments
 (0)