DEV Community

Gerasimos (Makis) Maropoulos
Gerasimos (Makis) Maropoulos

Posted on

How to use Iris and Basic authentication

Iris is a fast, simple yet fully featured and very efficient web framework for Go. It provides a beautifully expressive and easy to use foundation for your next website or API. One of the features that Iris offers the middleware/basicauth sub-package, which allows you to implement basic authentication for your web applications.

Basic authentication is a simple and widely used scheme that requires the client to provide a username and password to access a protected resource. The credentials are encoded with Base64 and sent in the HTTP header. However, they are not encrypted or hashed, so basic authentication should be used in conjunction with HTTPS to provide confidentiality.

In this article, we will show you how to use the basicauth middleware to add basic authentication to your Iris handlers.

Installing Iris and BasicAuth Middleware

To use the BasicAuth middleware, you need to install Iris first. You can do that by running the following command in your terminal:

go get github.com/kataras/iris/v12@latest
Enter fullscreen mode Exit fullscreen mode

This will download and install the latest version of Iris and its dependencies. You can also specify a specific version if you want.

Next, you need to import the middleware/basicauth sub-package in your Go code. You can do that by adding the following line at the top of your file:

import "github.com/kataras/iris/v12/middleware/basicauth"
Enter fullscreen mode Exit fullscreen mode

This will make the basicauth package available for your use.

Creating a basic authentication middleware

To create a basic authentication middleware, you need to use the basicauth.New function from the basicauth package. This function accepts a basicauth.Options struct that contains various options for configuring the middleware. The most important option is the Allow field, which is a function that takes a username and password as arguments and returns true if they are valid or false otherwise. You can use one of the helper methods from the basicauth package to create this function from different sources of valid credentials. They are:

  • basicauth.AllowUsers: This method takes a map of usernames and passwords and returns an Allow function that uses the given map as the source of valid credentials. This is useful if you want to create the Allow function from a predefined map of users.
  • basicauth.AllowUsersFile: This method takes a JSON or YAML filename and returns an Allow function that uses the file as the source of valid credentials. The file should contain an array of objects with username and password fields. This is useful if you want to store your users in an external file instead of in your code.
  • basicauth.BCRYPT: This method takes a UserAuthOptions struct and modifies it to use bcrypt hashing for comparing passwords. This is useful if you want to store hashed passwords instead of plain ones in your users map or file. You can pass this method as an argument to the basicauth.AllowUsers or basicauth.AllowUsersFile helper methods to create an Allow function that uses bcrypt hashing.

You can also set other options such as Realm, Expires, ErrorHandler and more.

The basicauth.New function returns an iris.Handler, which is a function that takes an iris.Context as an argument and performs some actions on it. You can register this handler as a middleware for your routes or parties using methods such as Use, UseGlobal, or UseRouter.

Here is an example of how to create and use a basic authentication middleware using a map of users:

package main

import (
    "github.com/kataras/iris/v12"
    "github.com/kataras/iris/v12/middleware/basicauth"
)

func main() {
    app := iris.New()

    // Create a map of usernames and passwords.
    users := map[string]string{
        "myusername": "mypassword",
        "admin":      "admin",
    }

    // Create an Allow function using basicauth.AllowUsers helper method.
    allow := basicauth.AllowUsers(users)

    // Create a basic authentication middleware using basicauth.New.
    auth := basicauth.New(basicauth.Options{
        Realm: basicauth.DefaultRealm,
        Allow: allow,
    })

    // Register the auth handler as a global middleware using UseGlobal.
    app.UseGlobal(auth)

    // Register some routes that require basic authentication.
    app.Get("/", func(ctx iris.Context) {
        username, password, _ := ctx.User()
        ctx.Writef("%s %s: You are authenticated", username, password)
    })

    app.Get("/admin", func(ctx iris.Context) {
        username, _, _ := ctx.User()
        if username == "admin" {
            ctx.WriteString("Hello admin")
        } else {
            ctx.StopWithText(iris.StatusForbidden, "Only admin can access this page")
        }
    })

    app.Get("/logout", func(ctx iris.Context) {
        ctx.Logout()
        ctx.Redirect("/")
    })

    app.Listen(":8080")
}
Enter fullscreen mode Exit fullscreen mode

Testing the basic authentication middleware

To test the basic authentication middleware, you can run the above code and visit http://localhost:8080 in your browser. You should see a prompt asking you for your username and password. If you enter one of the valid credentials from the users map, you should see a message saying that you are authenticated. If you enter an invalid credential, you should see an error message saying that authorization is required.

You can also visit http://localhost:8080/admin to see a page that is only accessible by the admin user. If you enter the admin credential, you should see a message saying hello admin. If you enter any other credential, you should see a message saying that only admin can access this page.

You can also visit http://localhost:8080/logout to log out from the basic authentication and clear the cookie. You should be redirected to the home page and see the prompt again if you refresh the page.

Conclusion

In this article, we have learned how to use the middleware/basicauth sub-package to create a basic authentication middleware for your Iris handlers. We have seen how to configure the middleware with various options, how to register it as a global or route-specific middleware, and how to test it in the browser. We have also seen how to use different helper methods to create the Allow function from different sources of valid credentials, and how to use bcrypt hashing to store hashed passwords. We have also seen how to use the Context.User() method to get the username and password of the authenticated user, and how to use the Context.Logout() method to log out from the basic authentication.

We hope that this article has helped you understand how to use Iris and basic authentication for your web applications. For more information and examples, you can visit the official documentation of Iris at https://www.iris-go.com/docs/#/?id=using-basic-authentication and the GitHub repository of Iris at https://github.com/kataras/iris/tree/master/_examples/auth/basicauth. Thank you for reading!

Top comments (0)