feat: add http interceptor function for auth and token endpoints

This commit is contained in:
Livio Amstutz 2020-02-06 11:12:00 +01:00
parent 7e2c22f99b
commit f0d17fd839
2 changed files with 26 additions and 5 deletions

View file

@ -41,6 +41,7 @@ type DefaultOP struct {
http *http.Server http *http.Server
decoder *schema.Decoder decoder *schema.Decoder
encoder *schema.Encoder encoder *schema.Encoder
interceptor HttpInterceptor
} }
type Config struct { type Config struct {
@ -98,6 +99,13 @@ func WithCustomUserinfoEndpoint(endpoint Endpoint) DefaultOPOpts {
} }
} }
func WithHttpInterceptor(h HttpInterceptor) DefaultOPOpts {
return func(o *DefaultOP) error {
o.interceptor = h
return nil
}
}
func NewDefaultOP(ctx context.Context, config *Config, storage Storage, opOpts ...DefaultOPOpts) (OpenIDProvider, error) { func NewDefaultOP(ctx context.Context, config *Config, storage Storage, opOpts ...DefaultOPOpts) (OpenIDProvider, error) {
err := ValidateIssuer(config.Issuer) err := ValidateIssuer(config.Issuer)
if err != nil { if err != nil {
@ -123,7 +131,7 @@ func NewDefaultOP(ctx context.Context, config *Config, storage Storage, opOpts .
p.discoveryConfig = CreateDiscoveryConfig(p, p.signer) p.discoveryConfig = CreateDiscoveryConfig(p, p.signer)
router := CreateRouter(p) router := CreateRouter(p, p.interceptor)
p.http = &http.Server{ p.http = &http.Server{
Addr: ":" + config.Port, Addr: ":" + config.Port,
Handler: router, Handler: router,

View file

@ -21,12 +21,25 @@ type OpenIDProvider interface {
HttpHandler() *http.Server HttpHandler() *http.Server
} }
func CreateRouter(o OpenIDProvider) *mux.Router { type HttpInterceptor func(http.HandlerFunc) http.HandlerFunc
var (
DefaultInterceptor = func(h http.HandlerFunc) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
h(w, r)
})
}
)
func CreateRouter(o OpenIDProvider, h HttpInterceptor) *mux.Router {
if h == nil {
h = DefaultInterceptor
}
router := mux.NewRouter() router := mux.NewRouter()
router.HandleFunc(oidc.DiscoveryEndpoint, o.HandleDiscovery) router.HandleFunc(oidc.DiscoveryEndpoint, o.HandleDiscovery)
router.HandleFunc(o.AuthorizationEndpoint().Relative(), o.HandleAuthorize) router.HandleFunc(o.AuthorizationEndpoint().Relative(), h(o.HandleAuthorize))
router.HandleFunc(o.AuthorizationEndpoint().Relative()+"/{id}", o.HandleAuthorizeCallback) router.HandleFunc(o.AuthorizationEndpoint().Relative()+"/{id}", h(o.HandleAuthorizeCallback))
router.HandleFunc(o.TokenEndpoint().Relative(), o.HandleExchange) router.HandleFunc(o.TokenEndpoint().Relative(), h(o.HandleExchange))
router.HandleFunc(o.UserinfoEndpoint().Relative(), o.HandleUserinfo) router.HandleFunc(o.UserinfoEndpoint().Relative(), o.HandleUserinfo)
router.HandleFunc(o.KeysEndpoint().Relative(), o.HandleKeys) router.HandleFunc(o.KeysEndpoint().Relative(), o.HandleKeys)
return router return router