Quick Start

This guide shows how to add email and password authentication to a Go application. Complete Installation first.

Create the plugin instance #

Authentication methods are plugins. Create the plugin instance from the built-in emailpassword plugin. All of its options are optional, so the zero value works.

auth.go
import "github.com/go-behemoth/behemoth/plugins/emailpassword"

plugin := emailpassword.New(emailpassword.Options{})

Prepare and boot the application #

Prepare collects the declarations of your plugins and schema. Boot connects them to a database and a router.

main.go
app, err := engine.Prepare(
    []core.Plugin{plugin},
    engine.PrepareConfig{},
)
if err != nil {
    log.Fatal(err)
}

db := postgres.NewPostgresAdapter(sqlDB, app.Resolver)
router := gin.New()

ac, err := engine.Boot(
    ctx,
    app,
    db,
    engine.BootConfig{
        Crypto: crypto.Config{
            // The master secret every key is derived from.
            Secrets: crypto.StaticSecretSource{
                Secrets: map[int]string{
                    1: os.Getenv("BEHEMOTH_SECRET"),
                },
                Current: 1,
            },
        },
        HTTP: ginadapter.New(router),
        Session: core.SessionConfig{
            ExpiresIn: 24 * time.Hour,
        },
        // The session token travels in a header.
        Router: httpapi.RouterConfig{
            Carrier: httpapi.TokenCarrierConfig{
                Delivery: httpapi.DeliveryHeader,
            },
        },
    },
)
if err != nil {
    log.Fatal(err)
}

This guide delivers the session token in a header, so that you can see it in the examples below. The default is a cookie, which suits a browser application. See Token delivery.

Configure email and password options #

To change the defaults, set the options you need:

go
plugin := emailpassword.New(emailpassword.Options{
    MinPasswordLength: 12,
    ValidatePassword: func(password string) error {
        if isBreached(password) {
            return errors.New("this password has appeared in a data breach")
        }
        return nil
    },
})

Mount the routes #

Pass a router adapter to BootConfig.HTTP and Behemoth mounts its routes on your router. Start your server as usual:

import ginadapter "github.com/go-behemoth/behemoth/plugins/adapters/gin"

router := gin.New()
ac, err := engine.Boot(
    ctx,
    app,
    db,
    engine.BootConfig{
        // ...
        HTTP: ginadapter.New(router),
    },
)
if err != nil {
    log.Fatal(err)
}

router.Run(":8080")

Behemoth mounts its routes under /api/auth by default (RouterConfig.BasePath). The following routes are available:

MethodEndpointDescription
POST/api/auth/sign-up/emailCreate a new account
POST/api/auth/sign-in/emailSign in with email and password
POST/api/auth/sign-outSign out and revoke the session

Test the routes #

With the server running, send the following requests:

bash
curl -X POST localhost:8080/api/auth/sign-up/email   -d '{"email":"ada@example.com","password":"correct horse battery"}'

curl -X POST localhost:8080/api/auth/sign-in/email   -d '{"email":"ada@example.com","password":"correct horse battery"}'

Protect routes #

The context that Boot returns exposes an Authenticator. It turns the session token of a request into a caller, in the same way that Behemoth's own routes do. Use it to protect a route of your own on your framework. The following Gin middleware reads the bearer token and refuses a request without a signed-in user:

go
func requireAuth(ac *core.AuthContext) gin.HandlerFunc {
    return func(c *gin.Context) {
        var cred *core.Credential
        header := c.GetHeader("Authorization")
        token, found := strings.CutPrefix(header, "Bearer ")
        if found && token != "" {
            cred = &core.Credential{
                Kind:  core.CredentialSession,
                Value: token,
            }
        }

        peer := identity.Peer{
            Transport: "http",
            IPAddress: c.ClientIP(),
            UserAgent: c.Request.UserAgent(),
        }
        caller, _ := ac.Authenticator.Authenticate(
            c.Request.Context(),
            cred,
            peer,
        )

        session, ok := caller.Session()
        if !ok {
            c.AbortWithStatusJSON(
                http.StatusUnauthorized,
                gin.H{"error": "sign in required"},
            )
            return
        }
        c.Set("session", session)
        c.Next()
    }
}

router.GET("/dashboard", requireAuth(ac), func(c *gin.Context) {
    session := c.MustGet("session").(identity.SessionRef)
    c.JSON(http.StatusOK, gin.H{"userId": session.UserID})
})

This middleware reads the token from the Authorization header, which matches the header delivery in this guide. With the cookie delivery, read the cookie instead, which is named session_token by default. For a route that you mount through Behemoth's router, add the httpapi.RequireSession middleware to the route instead. See Protect your own routes.

Call flows from code #

The routes are thin wrappers around two methods on the plugin. After Boot, call them from a CLI, a job, or a test:

go
user, err := plugin.SignUp(ctx, behemoth.M{
    "email":    "ada@example.com",
    "password": "correct horse battery",
})
if err != nil {
    log.Fatal(err)
}
log.Println("user created:", user.ID)

result, err := plugin.SignIn(
    ctx,
    emailpassword.EmailAndPasswordCredentials{
        Email:    "ada@example.com",
        Password: "correct horse battery",
    },
)
if err != nil {
    log.Fatal(err)
}
// result.User, result.Session, result.RawToken
log.Println("session created:", result.Session.ID)
Client libraries

Behemoth has no client library. Call the routes over HTTP.

Next steps #

Now that basic authentication works, explore the following topics:

  • Sessions: Session settings, token delivery, and protecting your own routes.
  • Email and password: Options, error responses, and password reset.
  • Hooks: Run your code at fixed points in sign-up, sign-in, and data writes.
  • Routers: Adapters for net/http, Gin, Echo, chi, and Fiber.
  • Migration CLI: Generate migrations for your database.
  • The examples/init directory: A complete application with migrations, hooks, and telemetry.