Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
bbigras opened this issue Jan 19, 2016 · 0 comments
Open

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

bbigras opened this issue Jan 19, 2016 · 0 comments

Comments

@bbigras
Copy link
Contributor

bbigras commented Jan 19, 2016

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)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant