Allow nil CORS policy to be set to disable CORS middleware

This commit is contained in:
Kory Prince 2023-11-13 18:31:39 -06:00
parent cd3cb17b2c
commit 37e01449e0
2 changed files with 15 additions and 10 deletions

View file

@ -98,13 +98,15 @@ type OpenIDProvider interface {
type HttpInterceptor func(http.Handler) http.Handler
type corsOptioner interface {
CORSOptions() cors.Options
CORSOptions() *cors.Options
}
func CreateRouter(o OpenIDProvider, interceptors ...HttpInterceptor) chi.Router {
router := chi.NewRouter()
if co, ok := o.(corsOptioner); ok {
router.Use(cors.New(co.CORSOptions()).Handler)
if opts := co.CORSOptions(); opts != nil {
router.Use(cors.New(*opts).Handler)
}
} else {
router.Use(cors.New(defaultCORSOptions).Handler)
}
@ -232,7 +234,7 @@ func NewProvider(config *Config, storage Storage, issuer func(insecure bool) (Is
storage: storage,
endpoints: DefaultEndpoints,
timer: make(<-chan time.Time),
corsOpts: defaultCORSOptions,
corsOpts: &defaultCORSOptions,
logger: slog.Default(),
}
@ -277,7 +279,7 @@ type Provider struct {
timer <-chan time.Time
accessTokenVerifierOpts []AccessTokenVerifierOpt
idTokenHintVerifierOpts []IDTokenHintVerifierOpt
corsOpts cors.Options
corsOpts *cors.Options
logger *slog.Logger
}
@ -437,7 +439,7 @@ func (o *Provider) Probes() []ProbesFn {
}
}
func (o *Provider) CORSOptions() cors.Options {
func (o *Provider) CORSOptions() *cors.Options {
return o.corsOpts
}
@ -601,7 +603,7 @@ func WithIDTokenHintVerifierOpts(opts ...IDTokenHintVerifierOpt) Option {
}
}
func WithCORSOptions(opts cors.Options) Option {
func WithCORSOptions(opts *cors.Options) Option {
return func(o *Provider) error {
o.corsOpts = opts
return nil

View file

@ -29,7 +29,7 @@ func RegisterServer(server Server, endpoints Endpoints, options ...ServerOption)
server: server,
endpoints: endpoints,
decoder: decoder,
corsOpts: defaultCORSOptions,
corsOpts: &defaultCORSOptions,
logger: slog.Default(),
}
@ -38,7 +38,10 @@ func RegisterServer(server Server, endpoints Endpoints, options ...ServerOption)
}
ws.createRouter()
return cors.New(ws.corsOpts).Handler(ws)
if ws.corsOpts != nil {
return cors.New(*ws.corsOpts).Handler(ws)
}
return ws
}
type ServerOption func(s *webServer)
@ -67,7 +70,7 @@ func WithDecoder(decoder httphelper.Decoder) ServerOption {
}
// WithServerCORSOptions sets the CORS policy for the Server's router.
func WithServerCORSOptions(opts cors.Options) ServerOption {
func WithServerCORSOptions(opts *cors.Options) ServerOption {
return func(s *webServer) {
s.corsOpts = opts
}
@ -87,7 +90,7 @@ type webServer struct {
router *chi.Mux
endpoints Endpoints
decoder httphelper.Decoder
corsOpts cors.Options
corsOpts *cors.Options
logger *slog.Logger
}