Skip to content

Improved code readability and RFC compliance #2795

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

suwakei
Copy link

@suwakei suwakei commented Jun 23, 2025

Proposal

1. Improved parsing of authentication information:

I currently use a for loop to split username and password, but we believe that using strings.Cut, available in Go 1.18 or later, would make the code simpler and more readable.

// basic_auth.go


				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)
+++					}
				}

2. Added Realm quoting in WWW-Authenticate header:

RFC 7617 requires that the value of the realm parameter be a quoted-string. In the current implementation, the default realm is unquoted. You can comply with this specification by always using strconv.Quote

// basic_auth.go
---	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

These changes will further improve the robustness and maintainability of the middleware.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant