connectauth
connectauth copied to clipboard
Flexible authentication for Connect handlers
connectauth (deprecated)
[!CAUTION] A variant of this package is now officially part of the Connect project! Use connectrpc.com/authn instead.
connectauth provides flexible authentication for Connect
servers written in Go. It works with any authentication function, covers both
unary and streaming RPCs, and runs efficiently.
Installation
go get go.akshayshah.org/connectauth
Usage
package main
import (
"context"
"fmt"
"net/http"
"connectrpc.com/connect"
"go.akshayshah.org/connectauth"
)
// Our authentication logic is just a function.
func authenticate(ctx context.Context, req *connectauth.Request) (any, error) {
const passphrase = "open-sesame"
if req.Header.Get("Authorization") != "Bearer "+passphrase {
// If authentication fails, we return an error. connectauth.Errorf is a
// convenient shortcut to produce an error coded with
// connect.CodeUnauthenticated.
return nil, connectauth.Errorf("try %q as a bearer token instead", passphrase)
}
// Once we've authenticated the request, we can return some information about
// the client. That information gets attached to the context passed to
// subsequent interceptors and our service implementation.
return "Ali Baba", nil
}
// This constructor would normally be generated by protoc-gen-connect-go. For
// this example, we'll use a small stub.
func NewHelloServiceHandler(svc any, opts ...connect.HandlerOption) (string, http.Handler) {
return "/hello.v1/Hello", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Service implementations can retrieve information about the authenticated
// caller from the context.
identity := connectauth.GetInfo(r.Context())
fmt.Fprintf(w, "Hello, %v!", identity)
})
}
func main() {
mux := http.NewServeMux()
mux.Handle(NewHelloServiceHandler(struct{}{}))
// Before starting the HTTP server, wrap the whole mux in our authenticating
// middleware.
middleware := connectauth.NewMiddleware(authenticate)
http.ListenAndServe("localhost:8080", middleware.Wrap(mux))
}
Status: Deprecated
This module is currently deprecated in favor of connectrpc.com/authn. This package isn't going anywhere, but users should migrate — the APIs are very similar!
Legal
Offered under the MIT license.