Testing Basic Authentication

In our first example we will use the iris/httptest subpackage to test Basic Authentication.

1. The main.go source file looks like that:

  1. package main
  2. import (
  3. "github.com/kataras/iris/v12"
  4. "github.com/kataras/iris/v12/middleware/basicauth"
  5. )
  6. func newApp() *iris.Application {
  7. app := iris.New()
  8. opts := basicauth.Options{
  9. Allow: basicauth.AllowUsers(map[string]string{"myusername": "mypassword"}),
  10. }
  11. authentication := basicauth.New(opts) // or just: basicauth.Default(map...)
  12. app.Get("/", func(ctx iris.Context) { ctx.Redirect("/admin") })
  13. // to party
  14. needAuth := app.Party("/admin", authentication)
  15. {
  16. //http://localhost:8080/admin
  17. needAuth.Get("/", h)
  18. // http://localhost:8080/admin/profile
  19. needAuth.Get("/profile", h)
  20. // http://localhost:8080/admin/settings
  21. needAuth.Get("/settings", h)
  22. }
  23. return app
  24. }
  25. func h(ctx iris.Context) {
  26. // username, password, _ := ctx.Request().BasicAuth()
  27. // third parameter it will be always true because the middleware
  28. // makes sure for that, otherwise this handler will not be executed.
  29. // OR:
  30. user := ctx.User().(*iris.SimpleUser)
  31. ctx.Writef("%s %s:%s", ctx.Path(), user.Username, user.Password)
  32. // ctx.Writef("%s %s:%s", ctx.Path(), username, password)
  33. }
  34. func main() {
  35. app := newApp()
  36. app.Listen(":8080")
  37. }

2. Now, create a main_test.go file and copy-paste the following.

  1. package main
  2. import (
  3. "testing"
  4. "github.com/kataras/iris/v12/httptest"
  5. )
  6. func TestNewApp(t *testing.T) {
  7. app := newApp()
  8. e := httptest.New(t, app)
  9. // redirects to /admin without basic auth
  10. e.GET("/").Expect().Status(httptest.StatusUnauthorized)
  11. // without basic auth
  12. e.GET("/admin").Expect().Status(httptest.StatusUnauthorized)
  13. // with valid basic auth
  14. e.GET("/admin").WithBasicAuth("myusername", "mypassword").Expect().
  15. Status(httptest.StatusOK).Body().Equal("/admin myusername:mypassword")
  16. e.GET("/admin/profile").WithBasicAuth("myusername", "mypassword").Expect().
  17. Status(httptest.StatusOK).Body().Equal("/admin/profile myusername:mypassword")
  18. e.GET("/admin/settings").WithBasicAuth("myusername", "mypassword").Expect().
  19. Status(httptest.StatusOK).Body().Equal("/admin/settings myusername:mypassword")
  20. // with invalid basic auth
  21. e.GET("/admin/settings").WithBasicAuth("invalidusername", "invalidpassword").
  22. Expect().Status(httptest.StatusUnauthorized)
  23. }

3. Open your command line and execute:

  1. $ go test -v