sig-auth/server/server.go

57 lines
1.2 KiB
Go
Raw Normal View History

2025-02-14 19:41:22 -05:00
package server
import (
"context"
"fmt"
"net/http"
"github.com/common-fate/httpsig"
"github.com/common-fate/httpsig/inmemory"
2025-02-17 19:55:53 -05:00
"github.com/common-fate/httpsig/verifier"
2025-02-14 19:41:22 -05:00
)
2025-02-17 19:55:53 -05:00
func Start(isCaddyAuth bool, keyDir verifier.KeyDirectory) error {
2025-02-14 19:41:22 -05:00
mux := http.NewServeMux()
verifier := httpsig.Middleware(httpsig.MiddlewareOpts{
NonceStorage: inmemory.NewNonceStorage(),
2025-02-17 19:55:53 -05:00
KeyDirectory: keyDir,
2025-02-16 13:51:12 -05:00
Tag: "auth",
2025-02-14 19:41:22 -05:00
Scheme: "http",
Authority: "localhost:8080",
OnValidationError: func(ctx context.Context, err error) {
fmt.Printf("validation error: %s\n", err)
},
OnDeriveSigningString: func(ctx context.Context, stringToSign string) {
fmt.Printf("string to sign:\n%s\n", stringToSign)
},
})
2025-02-16 13:51:53 -05:00
verifyHandler := verifier(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
2025-02-14 19:41:22 -05:00
attr := httpsig.AttributesFromContext(r.Context()).(string)
2025-02-16 13:51:53 -05:00
if isCaddyAuth {
w.Header().Add("Remote-User", attr)
} else {
msg := fmt.Sprintf("hello, %s!", attr)
w.Write([]byte(msg))
}
}))
var handler http.Handler
if isCaddyAuth {
handler = rewriteHeaders(verifyHandler)
} else {
handler = verifyHandler
}
mux.Handle("/", handler)
2025-02-14 19:41:22 -05:00
err := http.ListenAndServe("localhost:8080", mux)
return err
}