import (
"github.com/cego/go-lib/v2/logger"
"github.com/cego/go-lib/v2/renderer"
"github.com/cego/go-lib/v2/forwardauth"
"github.com/cego/go-lib/v2/oidcauth"
"github.com/cego/go-lib/v2/oidcclient"
"github.com/cego/go-lib/v2/headers"
"github.com/cego/go-lib/v2/serve"
"github.com/cego/go-lib/v2/periodic"
)l := logger.New()
l.Debug("Very nice")
err := errors.New("An error")
l.Error("An error occurred in readme", logger.GetSlogAttrFromError(err))
handleFunc := func(writer http.ResponseWriter, request *http.Request) {
l.Debug("Very nice", logger.GetSlogAttrFromRequest(request))
}
// With custom log level
l := logger.NewWithLevel(slog.LevelInfo)
// Set as global slog default
slog.SetDefault(l)
// Testing with mock logger
l := loggertest.NewMock()
r := renderer.New(l)l := logger.New()
r := renderer.New(l)
handleFunc := func(writer http.ResponseWriter, request *http.Request) {
r.Text(w, http.StatusOK, "Action package excitement !!!")
}mux := http.NewServeMux()
fa := forwardauth.New(l, "https://sso.example.com/auth", "myservice.example.com")
mux.Handle("/data", fa.Handler(reverseProxy))
mux.Handle("/data", fa.HandlerFunc(func (w http.ResponseWriter, req *http.Request) {
_,_ = w.Write()
}))mux := http.NewServeMux()
httpClient := &http.Client{Timeout: time.Duration(1) * time.Second}
fa := forwardauth.New(l, "https://sso.example.com/auth", "myservice.example.com", forwardauth.WithHTTPClient(httpClient))
mux.Handle("/data", fa.Handler(reverseProxy))
mux.Handle("/data", fa.HandlerFunc(func (w http.ResponseWriter, req *http.Request) {
_,_ = w.Write()
}))Authorization code flow with PKCE for browsers, bearer tokens for api clients. The verified id token is the session cookie, so there is no session store. When the provider hands out a refresh token, it is kept in a second cookie and renews the session when the id token runs out.
mux := http.NewServeMux()
auth, err := oidcauth.New(context.Background(), l, oidcauth.Config{
Issuer: "https://keycloak.example.com/realms/cego",
ClientID: "myservice",
ClientSecret: os.Getenv("MYSERVICE_OIDC_CLIENT_SECRET"),
BaseURL: "https://myservice.example.com",
})
auth.Register(mux) // Adds GET /auth/login, GET /auth/callback and POST /auth/logout
mux.Handle("GET /{$}", auth.HandlerFunc(index)) // Authenticated
mux.Handle("GET /things", auth.HandlerFunc(things, "reader", "tool-admin")) // Either role
mux.Handle("POST /things/{id}/delete", auth.HandlerFunc(del, "tool-admin")) // That role
r.Use(auth.Middleware("reader")) // The same gate as chi middleware
// Inside a wrapped handler, or a template
user := oidcauth.UserFromContext(r.Context())
user.HasRole("tool-admin")
user.HasAnyRole("reader", "tool-admin")- Register
<BaseURL>/auth/callbackon the client, or the provider rejects the login - Roles are read from
client_rolesandresource_access.<client>.roles - Issuer and base url must be https, except on loopback
- A session lasts as long as the id token. A refresh renews it without a redirect, and reads the roles anew, until the provider ends the session
- A refresh token is exchanged once per process for the requests that arrive holding it. Behind several replicas, a provider that rotates refresh tokens sends some of those requests back to login
- Each auth instance allows 32 concurrent refresh/revocation operations and up to 1024 cached token hashes;
excess refresh requests get
503. Exchanges time out after 10 seconds, including with a custom HTTP client. Apply request rate limiting before this middleware to protect the provider from sustained traffic - No session: browsers go to the provider, htmx gets
HX-Redirect, api clients get401 - Logout is a
POST: it clears both cookies, invalidates local refresh results, and attempts token revocation when discovery advertisesrevocation_endpointwithclient_secret_basic(the default) orclient_secret_post. The attempt takes at most 10 seconds; failures are logged and logout continues. Refresh does not require revocation support. The provider logout redirect contains no token and may ask the user to confirm; that flow must complete to end the provider session - If revocation fails or is unavailable, copied refresh tokens may remain usable until the provider invalidates them. Offline tokens need explicit revocation; ending the browser session alone is insufficient
- Already-issued id tokens remain valid until expiry, so keep that lifetime short. Other replicas can still reuse a cached refresh result for up to 10 seconds (never beyond the id token's expiry)
- Cookies are
__Host-prefixed, secure andSameSite=Lax, which is not a CSRF token Userimplementsslog.LogValuer, so"user", userlogs the ecs shaped group
auth, err := oidcauth.New(ctx, l, cfg,
oidcauth.WithHTTPClient(httpClient), // default timeout 10s
oidcauth.WithScopes("openid", "email"), // default openid, profile, email
oidcauth.WithRolesClaim("realm_roles"), // default client_roles
oidcauth.WithCookiePrefix("myservice"), // default oidcauth
oidcauth.WithBearerAudience("myservice-api"), // default the client id
)The outbound counterpart to OidcAuth: the client credentials grant, for calling another service that verifies bearer tokens.
tokens, err := oidcclient.New(oidcclient.Config{
Issuer: "https://keycloak.example.com/realms/cego",
ClientID: "myservice",
ClientSecret: os.Getenv("MYSERVICE_OIDC_CLIENT_SECRET"),
})
// Set the header yourself
token, err := tokens.Token(ctx)
req.Header.Set(headers.Authorization, "Bearer "+token)
// Or let an http client do it on every request
client := tokens.HTTPClient(&http.Client{Timeout: 30 * time.Second})
res, err := client.Do(req)- The issuer is not contacted until the first
Tokencall, so a provider that is briefly unreachable does not stop the service from starting - Tokens are cached and replaced
DefaultRefreshBeforeahead of their expiry, so a token handed to a caller does not expire in flight - Concurrent callers share one request to the issuer
- HTTP clients reject cross-origin redirects rather than forwarding the bearer token
- The roles and audiences in the token come from the provider's configuration of the client, not from this package
tokens, err := oidcclient.New(cfg,
oidcclient.WithHTTPClient(httpClient), // default timeout 10s
oidcclient.WithScopes("profile", "email"), // default the provider's own
oidcclient.WithRefreshBefore(10*time.Second), // default 30s
)req.Header.Get(headers.Authorization)
req.Header.Get(headers.XForwardedFor)Available constants: XForwardedProto, XForwardedMethod, XForwardedHost, XForwardedUri, XForwardedFor, Accept, UserAgent, Cookie, Authorization, RemoteUser, ContentType
Context-aware periodic task execution with jitter support.
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()
periodic.Run(ctx, 2*time.Second, time.Duration(rand.Intn(1000))*time.Millisecond, func() {
fmt.Println("runs every 2 seconds until ctx is cancelled")
})Graceful HTTP server shutdown with a configurable delay for load balancer deregistration.
srv := serve.WithDefaults(&http.Server{Addr: ":8080", Handler: myHandler})
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()
err := serve.ListenAndServe(ctx, srv, slog.Default())