Autostrada
Autostrada
Create a new codebase Get Autostrada Plus
Documentation Changelog Roadmap Give feedback
Login

DocumentationTraditional web application › Basic auth

Basic auth

If you select the Basic auth option when generating your codebase, the cmd/web/middleware.go file will include a basicAuth() middleware function.

You can use this to protect either your entire application or specific routes using HTTP basic authentication.

If you look in the generated cmd/web/routes.go file, you'll see that there is a GET /restricted-basic-auth route that provides an example of using this middleware. When you visit this route, you can authenticate using the default credentials:

User name: admin
Password: pa55word

If you input an incorrect user name or password, the application will use the basicAuthenticationRequired() helper – which is defined in cmd/web/errors.go – to send a 401 Unauthorized response with a plaintext error message and the appropriate WWW-Authenticate header.

If you selected the custom error pages option when generating your codebase, the basicAuthenticationRequired() helper will render the pages/errors/401.tmpl error page instead of sending a plaintext response.

Configuring the credentials

You can (and should!) configure the middleware to use your own credentials.

If you're using command-line flags for configuration, you can set them via the --basic-auth-username and --basic-auth-hashed-password flags. For example:

$ go run ./cmd/web --basic-auth-username='alice' --basic-auth-hashed-password='$2a$10$xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'

If you’re using environment variables, set BASIC_AUTH_USERNAME and BASIC_AUTH_HASHED_PASSWORD instead. For example:

$ export BASIC_AUTH_USERNAME='alice'
$ export BASIC_AUTH_HASHED_PASSWORD='$2a$10$xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'

Important: The value for --basic-auth-hashed-password or BASIC_AUTH_HASHED_PASSWORD must be a bcrypt hash of the password, not the plaintext password itself.

An easy way to generate a bcrypt hash for a password is to use the gophers.dev/cmds/bcrypt-tool package like so:

$ go run gophers.dev/cmds/bcrypt-tool@latest hash 'your_pa55word'