Skip to content

What is the best way to auth using an external source like LDAP? #32

@bbigras

Description

@bbigras

I would like to use go-http-auth to authenticate users with a LDAP server.

I'm able to do it with the following code but I would like to avoid having to copy code from go-http-auth (code between lines comments).

package main

import (
    "encoding/base64"
    "fmt"
    "net/http"
    "strings"

    "github.com/abbot/go-http-auth"
)

type myBasicAuth struct {
    base auth.BasicAuth
}

func (a *myBasicAuth) CheckAuth(r *http.Request) string {
    // --------------------------------------
    s := strings.SplitN(r.Header.Get("Authorization"), " ", 2)
    if len(s) != 2 || s[0] != "Basic" {
        return ""
    }

    b, err := base64.StdEncoding.DecodeString(s[1])
    if err != nil {
        return ""
    }
    pair := strings.SplitN(string(b), ":", 2)
    if len(pair) != 2 {
        return ""
    }
    user, password := pair[0], pair[1]
    // --------------------------------------

    fmt.Printf("user: %s, password: %s\n", user, password)

    // ** ldap code here **

    return ""
}

func (a *myBasicAuth) Wrap(wrapped auth.AuthenticatedHandlerFunc) http.HandlerFunc {
    // --------------------------------------
    return func(w http.ResponseWriter, r *http.Request) {
        if username := a.CheckAuth(r); username == "" {
            a.base.RequireAuth(w, r)
        } else {
            ar := &auth.AuthenticatedRequest{Request: *r, Username: username}
            wrapped(w, ar)
        }
    }
    // --------------------------------------
}

func handle(w http.ResponseWriter, r *auth.AuthenticatedRequest) {
    fmt.Fprintf(w, "<html><body><h1>Hello, %s!</h1></body></html>", r.Username)
}

func main() {
    authenticator := &myBasicAuth{auth.BasicAuth{Realm: "example.com"}}
    http.HandleFunc("/", authenticator.Wrap(handle))
    http.ListenAndServe("127.0.0.1:8080", nil)
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions