@@ -117,3 +117,64 @@ func TestBasicAuth(t *testing.T) {
117117})
118118}
119119}
120+
121+ func TestBasicAuthRealm (t * testing.T ) {
122+ e := echo .New ()
123+ mockValidator := func (u , p string , c echo.Context ) (bool , error ) {
124+ return false , nil // Always fail to trigger WWW-Authenticate header
125+ }
126+
127+ tests := []struct {
128+ name string
129+ realm string
130+ expectedAuth string
131+ }{
132+ {
133+ name : "Default realm" ,
134+ realm : "Restricted" ,
135+ expectedAuth : `basic realm="Restricted"` ,
136+ },
137+ {
138+ name : "Custom realm" ,
139+ realm : "My API" ,
140+ expectedAuth : `basic realm="My API"` ,
141+ },
142+ {
143+ name : "Realm with special characters" ,
144+ realm : `Realm with "quotes" and \backslashes` ,
145+ expectedAuth : `basic realm="Realm with \"quotes\" and \\backslashes"` ,
146+ },
147+ {
148+ name : "Empty realm (falls back to default)" ,
149+ realm : "" ,
150+ expectedAuth : `basic realm="Restricted"` ,
151+ },
152+ {
153+ name : "Realm with unicode" ,
154+ realm : "测试领域" ,
155+ expectedAuth : `basic realm="测试领域"` ,
156+ },
157+ }
158+
159+ for _ , tt := range tests {
160+ t .Run (tt .name , func (t * testing.T ) {
161+ req := httptest .NewRequest (http .MethodGet , "/" , nil )
162+ res := httptest .NewRecorder ()
163+ c := e .NewContext (req , res )
164+
165+ h := BasicAuthWithConfig (BasicAuthConfig {
166+ Validator : mockValidator ,
167+ Realm : tt .realm ,
168+ })(func (c echo.Context ) error {
169+ return c .String (http .StatusOK , "test" )
170+ })
171+
172+ err := h (c )
173+
174+ var he * echo.HTTPError
175+ errors .As (err , & he )
176+ assert .Equal (t , http .StatusUnauthorized , he .Code )
177+ assert .Equal (t , tt .expectedAuth , res .Header ().Get (echo .HeaderWWWAuthenticate ))
178+ })
179+ }
180+ }
0 commit comments