Basic Authentication

HTTP Basic Authentication is the simplest technique for enforcing access controls to web resources because it does not require cookies, session identifiers, or login pages; rather, HTTP Basic authentication uses standard fields in the HTTP header.

The Basic Authentication mechanism provides no confidentiality protection for the transmitted credentials. They are merely encoded with Base64 in transit, but not encrypted or hashed in any way. Therefore, basic authentication is typically used in conjunction with HTTPS to provide confidentiality.

Because the Basic Authentication field has to be sent in the header of each HTTP request, the web browser needs to cache credentials for a reasonable period of time to avoid constantly prompting the user for their username and password. Caching policy differs between browsers.

HTTP does not provide a method for a web server to instruct the client to "log out" the user. However, the Iris Basic Authentication middleware features an expiration field which you can set to re-ask for user credentials.


The Basic Authentication middleware is included with the Iris framework, so you do not need to install it separately.

1. Import the middleware

import ""

2. Configure the middleware with its Config:

basicAuthConfig := basicauth.Config{
Users: map[string]string{
"user": "pass",
Realm: "Authorization Required",
Expires: 2 * time.Hour,

3. Initialize the middleware:

basicAuth := basicauth.New(basicAuthConfig)

4. Register the middleware:

// Register to all matched routes
// under a Party and its children.
// OR/and register to all http error routes.
// OR register under a path prefix of a specific Party,
// including all http errors of this path prefix.
// OR register to a specific Route before its main handler.
app.Post("/protected", basicAuth, routeHandler)

5. Retrieve the username & password:

func routeHandler(ctx iris.Context) {
username, password, _ := ctx.Request().BasicAuth()
// [...]


Let's learn how we can test operations like basic authentication with the Iris httptest package using its WithBasicAuth method.

1. Import the httptest subpackage:

import httptest"

2. Initialize the tester object inside your test function, it requires the testing.T and iris.Application instances:

e := httptest.New(t, app)

3. Create a test case and use its WithBasicAuth method to create a request using basic authentication credentials:

e.POST("/protected").WithBasicAuth("user", "pass").

Full code example can be found at: _examples/auth/basicauth

That's all. Easy!