debian-forge-composer/internal/auth/jwt_auth_handler.go
sanne 4a057bf3d5 auth: OpenID/OAUth2 middleware
2 configurations for the listeners are now possible:
- enableJWT=false with client ssl auth
- enableJWT=true with https

Actual verification of the tokens is handled by
https://github.com/openshift-online/ocm-sdk-go.

An authentication handler is run as the top level handler, before any
routing is done. Routes which do not require authentication should be
listed as exceptions.

Authentication can be restricted using an ACL file which allows
filtering based on JWT claims. For more information see the inline
comments in ocm-sdk/authentication.

As an added quirk the `-v` flag for the osbuild-composer executable was
changed to `-verbose` to avoid flag collision with glog which declares
the `-v` flag in the package `init()` function. The ocm-sdk depends on
glog and pulls it in.
2021-09-04 02:48:52 +02:00

59 lines
1.3 KiB
Go

package auth
import (
"context"
"crypto/x509"
"fmt"
"io/ioutil"
"net/http"
"github.com/openshift-online/ocm-sdk-go/authentication"
"github.com/openshift-online/ocm-sdk-go/logging"
)
// When using this handler for auth, it should be run as high up as possible.
// Exceptions can be registered in the `exclude` slice
func BuildJWTAuthHandler(keysURL, caFile, aclFile string, exclude []string, next http.Handler) (handler http.Handler, err error) {
logBuilder := logging.NewGoLoggerBuilder()
if caFile != "" {
logBuilder = logBuilder.Debug(true)
}
logger, err := logBuilder.Build()
if err != nil {
return
}
logger.Info(context.Background(), aclFile)
builder := authentication.NewHandler().
Logger(logger).
KeysURL(keysURL)
// Used during testing
if caFile != "" {
logger.Warn(context.Background(),
"A custom CA is specified to verify jwt tokens, this shouldn't be enabled in a production setting.")
caPEM, err := ioutil.ReadFile(caFile)
if err != nil {
return nil, err
}
pool := x509.NewCertPool()
ok := pool.AppendCertsFromPEM(caPEM)
if !ok {
return nil, fmt.Errorf("Unable to load jwt ca cert %s.", caFile)
}
builder = builder.KeysCAs(pool)
}
if aclFile != "" {
builder = builder.ACLFile(aclFile)
}
for _, e := range exclude {
builder = builder.Public(e)
}
handler, err = builder.Next(next).Build()
return
}