LogoPly
Middleware

Basic Auth

HTTP Basic authentication with static users or a custom validator.

Basic Auth

middleware.BasicAuth protects routes with HTTP Basic authentication.

app.Use(middleware.BasicAuth([]middleware.BasicAuthUser{
	{Username: "admin", Password: "secret"},
}))

A missing or invalid credential returns 401 Unauthorized with a WWW-Authenticate challenge. The default realm is Restricted.

Options

app.Use(middleware.BasicAuth(
	[]middleware.BasicAuthUser{
		{Username: "admin", Password: "secret"},
	},
	middleware.BasicAuthOptions{Realm: "Ply Admin"},
))
OptionDefaultDescription
RealmRestrictedRealm shown by the browser login prompt

Custom validation

Use BasicAuthWithValidator when users come from a database or another store:

app.Use(middleware.BasicAuthWithValidator(
	func(username, password string) bool {
		user, err := findUser(username)
		if err != nil {
			return false
		}
		return checkPassword(user.Hash, password)
	},
	middleware.BasicAuthOptions{Realm: "Ply Admin"},
))

The validator runs for every request, so keep it fast. Cache user records when the lookup is expensive.

Session values

On success the middleware stores both values in the request session:

username := c.GetSession("username")
password := c.GetSession("password")

password is stored because the middleware puts the submitted credentials in the session. Avoid reading or logging it unless a downstream system needs the credential. For normal authorization, use only username.

Security notes

  • Basic authentication sends base64-encoded credentials, not encrypted ones. Use HTTPS.
  • The built-in user comparison uses constant-time comparison.
  • Do not put real credentials in source code. Load them from environment variables or a secret manager.
  • Basic auth has no logout or session expiry. The browser keeps sending the header until it is closed or the URL changes.
  • For browser applications, prefer a session or token flow with CSRF protection over Basic auth.