ldapauthecho

package module
v1.2.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 27, 2026 License: MIT Imports: 3 Imported by: 0

README

Echo middleware for ldap-authenticator

LDAP authentication for Echo, built on github.com/ctolon/ldap-authenticator.

go get github.com/ctolon/ldap-authenticator/contrib/echo

Why this is a separate module

The root package promises exactly one direct dependency, github.com/go-ldap/ldap/v3, and means it — a CI job fails the build if that stops being true. Framework middleware cannot live there without breaking that promise, so it lives here instead. Importing ldapauth never puts Echo in your build graph; importing this module is how you ask for it.

The policy — realms, group requirements, status codes, response padding — lives in the root module's httpauth package and is shared with the net/http, Gin, Echo, and Fiber adapters alike. There is one implementation of "what a 403 means here", not four.

Basic auth

auth, err := ldapauth.New(
    ldapauth.WithURL("ldaps://dc1.corp.example:636"),
    ldapauth.WithDirectBind("uid={{username}},ou=people,dc=corp,dc=example"),
    ldapauth.WithMemberOfGroups(),
)
if err != nil {
    log.Fatal(err)
}
defer auth.Close()

e := echo.New()

private := e.Group("", ldapauthecho.BasicAuth(auth,
    httpauth.WithRealm("corp"),
    httpauth.RequireAnyGroup("developers", "ops"),
    httpauth.WithMinimumDuration(100*time.Millisecond),
))

private.GET("/me", func(c echo.Context) error {
    return c.JSON(http.StatusOK, ldapauthecho.MustIdentity(c))
})

The middleware writes the rejection itself and returns nil rather than returning an echo.HTTPError. That is deliberate: Echo's default error handler would turn a bare 401 into a response body describing why the login failed, which is precisely what a rejection should not do.

Login

e.POST("/login", ldapauthecho.LoginHandler(auth,
    func(c echo.Context, identity ldapauth.Identity) error {
        // Start whatever a session is in your application. This library
        // deliberately does not decide that for you.
        return c.JSON(http.StatusOK, map[string]any{"dn": identity.GetDN()})
    },
))

Credentials are read from a JSON body, a form body, or a Basic header — whichever the request carries.

Reading the identity

identity, ok := ldapauthecho.IdentityFrom(c)     // the interface
principal, ok := ldapauthecho.PrincipalFrom(c)   // the concrete struct
identity := ldapauthecho.MustIdentity(c)         // panics if absent

The identity is put in both the Echo context, under ldapauthecho.ContextKey, and the request context, so a plain http.Handler further down the chain can read it with httpauth.IdentityFrom(r.Context()).

What the caller sees

200 authenticated, and in the required groups
400 the request was not a login: no username, an empty password
401 wrong or absent credentials, with a WWW-Authenticate challenge
403 the credentials were right and the groups were not
503 the directory could not answer

The body is empty by default: a rejection that explains itself is a rejection that helps somebody guess. httpauth.WithErrorHandler replaces that if your API has a shape of its own.

Options

Every option is an httpauth.Option, shared with the other adapters: WithRealm, RequireAnyGroup, RequireAllGroups, WithMinimumDuration, WithErrorHandler, WithSkip, WithMaxBodyBytes. All of them are applied here, including the two — the skip predicate and the body limit — that this adapter quietly ignored before v1.0.

An option that does not validate panics, because middleware is wired at startup and there is nowhere to return an error to. Use httpauth.NewPolicy if you would rather handle it.

Running the example

go run ./example
curl -u alice:s3cret localhost:8080/me

It runs against the in-memory directory in ldaptest, so there is no LDAP server to install.

More

Documentation

Overview

Package ldapauthecho is Echo middleware for github.com/ctolon/ldap-authenticator.

It is a separate module so that the root package can promise a single dependency and mean it. The policy — realms, group requirements, status codes, response padding — lives in the httpauth package of the root module and is shared with the other framework adapters.

e := echo.New()
e.Use(ldapauthecho.BasicAuth(auth, httpauth.RequireAnyGroup("developers")))
e.GET("/me", func(c echo.Context) error {
    return c.JSON(200, ldapauthecho.MustIdentity(c))
})

Index

Constants

View Source
const ContextKey = "ldapauth.identity"

ContextKey is the key the identity is stored under in the Echo context, for handlers that would rather use c.Get than the request context.

Variables

This section is empty.

Functions

func BasicAuth

func BasicAuth(auth ldapauth.Authenticator, opts ...httpauth.Option) echo.MiddlewareFunc

BasicAuth returns middleware that authenticates every request with HTTP Basic credentials.

It writes the rejection itself and returns nil rather than returning an echo.HTTPError, so that Echo's error handler cannot turn a bare 401 into a response body describing why the login failed.

func IdentityFrom

func IdentityFrom(c echo.Context) (ldapauth.Identity, bool)

IdentityFrom returns the identity the middleware authenticated.

func LoginHandler

func LoginHandler(
	auth ldapauth.Authenticator,
	onSuccess func(c echo.Context, p ldapauth.Identity) error,
	opts ...httpauth.Option,
) echo.HandlerFunc

LoginHandler returns a handler that reads credentials from the request — JSON body, form body, or Basic header — and hands the authenticated principal to onSuccess.

func MustIdentity

func MustIdentity(c echo.Context) ldapauth.Identity

MustIdentity returns the authenticated identity and panics if there is none, for handlers that are only ever mounted behind BasicAuth.

func PrincipalFrom

func PrincipalFrom(c echo.Context) (*ldapauth.Principal, bool)

PrincipalFrom returns the identity as the concrete ldapauth.Principal, for the common case where the mapper was not replaced and reading fields is nicer than calling accessors.

Types

This section is empty.

Directories

Path Synopsis
Command example is an Echo server authenticating against the in-memory directory, so it runs with no LDAP server anywhere.
Command example is an Echo server authenticating against the in-memory directory, so it runs with no LDAP server anywhere.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL