mirror of
				https://github.com/labstack/echo.git
				synced 2025-10-30 23:57:38 +02:00 
			
		
		
		
	Improve BasicAuth middleware: use strings.Cut and RFC compliance
- Replace manual for loop with strings.Cut for credential parsing - Simplify realm handling to always quote according to RFC 7617 - Improve code readability and maintainability Fixes #2794 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
		| @@ -84,27 +84,21 @@ func BasicAuthWithConfig(config BasicAuthConfig) echo.MiddlewareFunc { | ||||
| 				} | ||||
|  | ||||
| 				cred := string(b) | ||||
| 				for i := 0; i < len(cred); i++ { | ||||
| 					if cred[i] == ':' { | ||||
| 						// Verify credentials | ||||
| 						valid, err := config.Validator(cred[:i], cred[i+1:], c) | ||||
| 						if err != nil { | ||||
| 							return err | ||||
| 						} else if valid { | ||||
| 							return next(c) | ||||
| 						} | ||||
| 						break | ||||
| 				user, pass, ok := strings.Cut(cred, ":") | ||||
| 				if ok { | ||||
| 					// Verify credentials | ||||
| 					valid, err := config.Validator(user, pass, c) | ||||
| 					if err != nil { | ||||
| 						return err | ||||
| 					} else if valid { | ||||
| 						return next(c) | ||||
| 					} | ||||
| 				} | ||||
| 			} | ||||
|  | ||||
| 			realm := defaultRealm | ||||
| 			if config.Realm != defaultRealm { | ||||
| 				realm = strconv.Quote(config.Realm) | ||||
| 			} | ||||
|  | ||||
| 			// Need to return `401` for browsers to pop-up login box. | ||||
| 			c.Response().Header().Set(echo.HeaderWWWAuthenticate, basic+" realm="+realm) | ||||
| 			// Realm is case-insensitive, so we can use "basic" directly. See RFC 7617. | ||||
| 			c.Response().Header().Set(echo.HeaderWWWAuthenticate, basic+" realm="+strconv.Quote(config.Realm)) | ||||
| 			return echo.ErrUnauthorized | ||||
| 		} | ||||
| 	} | ||||
|   | ||||
		Reference in New Issue
	
	Block a user