Documentation
¶
Overview ¶
Example (BackendForAuthentication) ¶
package main
import (
"fmt"
"log"
"net/http"
"strings"
"github.com/orijtech/authmid"
"github.com/orijtech/authmid/backend/redis"
)
func main() {
backend, err := redis.New("keys", "redis://localhost:6379")
if err != nil {
log.Fatal(err)
}
ac := &apiChecker{
backend: backend,
next: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Authenticated pong!")
}),
hdrKey: "DEMO-ACCESS-APIKEY",
}
http.Handle("/ping", ac)
http.HandleFunc("/reg", func(w http.ResponseWriter, r *http.Request) {
qv := r.URL.Query()
key, secret := qv.Get("key"), qv.Get("secret")
if err := backend.UpsertSecret(key, secret); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
})
addr := ":8777"
log.Printf("Serving on: %s", addr)
if err := http.ListenAndServe(addr, nil); err != nil {
log.Fatal(err)
}
}
type apiChecker struct {
backend authmid.Backend
next http.Handler
hdrKey string
}
func (ac *apiChecker) ServeHTTP(w http.ResponseWriter, r *http.Request) {
apiKey := r.Header.Get(ac.hdrKey)
if strings.TrimSpace(apiKey) == "" {
http.Error(w, "expecting a non-blank API Key", http.StatusBadRequest)
return
}
secret, err := ac.backend.LookupSecret(apiKey)
if err != nil {
log.Printf("looking up secret: err: %v", err)
http.Error(w, "failed to lookup the secret", http.StatusBadRequest)
return
}
log.Printf("secret: %s\n", secret)
ac.next.ServeHTTP(w, r)
}
Output:
Example (InPlainServer) ¶
http.Handle("/", authmid.Middleware(&sampleAuthChecker{}, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Authenticated pong!")
})))
Example (Middleware) ¶
srv := httptest.NewServer(authmid.Middleware(&sampleAuthChecker{}, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
body, _ := ioutil.ReadAll(r.Body)
fmt.Fprintf(w, "Well authenticated, and here is your body: %s", body)
})))
defer srv.Close()
// The client will then authenticate like this
req := makeReq("POST", []byte(`{"name": "foo", "age": 99}`), authKey1)
req.URL, _ = url.Parse(srv.URL)
res, err := http.DefaultClient.Do(req)
if err != nil {
log.Fatal(err)
}
defer res.Body.Close()
blob, _ := ioutil.ReadAll(res.Body)
fmt.Printf("response: %s\n", blob)
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
Functions ¶
func Middleware ¶
func Middleware(vf Authenticator, next http.Handler) http.Handler
Types ¶
type Authenticator ¶
type Authenticator interface {
ReadOnlyBackend
HTTPAuthMiddleware
}
type Backend ¶
type Backend interface {
ReadOnlyBackend
WriteBackend
Close() error
}
type CodedError ¶
type ExcludeMethodAndPather ¶
type ExcludeMethodAndPather interface {
ExcludeMethodAndPath() bool
}
type HTTPAuthMiddleware ¶
type ReadOnlyBackend ¶
Click to show internal directories.
Click to hide internal directories.