From f397c30caf9c3c16f1c9f9c4752a2b2374f27e9f Mon Sep 17 00:00:00 2001 From: "Gerasimos (Makis) Maropoulos" Date: Thu, 3 Mar 2022 02:31:01 +0200 Subject: [PATCH] cors: add vary header looking for a CORS middleware with more options? Take a look at iris-contrib/middleware/cors instead --- README.md | 2 +- middleware/cors/cors.go | 23 ++++++++++++++++++----- 2 files changed, 19 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 82ab074e..f47c2836 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ # News -> This is the under-**development branch**. Stay tuned for the upcoming release [v12.2.0](HISTORY.md#Next). Looking for a stable release? Head over to the [v12.1.8 branch](https://github.com/kataras/iris/tree/v12.1.8) instead. +> This is the under-**development branch** - contains the latest and greatest features. Stay tuned for the upcoming release [v12.2.0](HISTORY.md#Next). Looking for a more stable release? Head over to the [v12.1.8 branch](https://github.com/kataras/iris/tree/v12.1.8) instead. > > ![](https://iris-go.com/images/cli.png) Try the official [Iris Command Line Interface](https://github.com/kataras/iris-cli) today! diff --git a/middleware/cors/cors.go b/middleware/cors/cors.go index 6e970a67..3acb1a82 100644 --- a/middleware/cors/cors.go +++ b/middleware/cors/cors.go @@ -267,17 +267,30 @@ const ( allowCredentialsHeader = "Access-Control-Allow-Credentials" referrerPolicyHeader = "Referrer-Policy" exposeHeadersHeader = "Access-Control-Expose-Headers" - - allowMethodsHeader = "Access-Control-Allow-Methods" - allowAllMethodsValue = "*" - allowHeadersHeader = "Access-Control-Allow-Headers" - maxAgeHeader = "Access-Control-Max-Age" + requestMethodHeader = "Access-Control-Request-Method" + requestHeadersHeader = "Access-Control-Request-Headers" + allowMethodsHeader = "Access-Control-Allow-Methods" + allowAllMethodsValue = "*" + allowHeadersHeader = "Access-Control-Allow-Headers" + maxAgeHeader = "Access-Control-Max-Age" + varyHeader = "Vary" ) +func (c *CORS) addVaryHeaders(ctx *context.Context) { + ctx.Header(varyHeader, originRequestHeader) + + if ctx.Method() == http.MethodOptions { + ctx.Header(varyHeader, requestMethodHeader) + ctx.Header(varyHeader, requestHeadersHeader) + } +} + // Handler method returns the Iris CORS Handler with basic features. // Note that the caller should NOT modify any of the CORS instance fields afterwards. func (c *CORS) Handler() context.Handler { return func(ctx *context.Context) { + c.addVaryHeaders(ctx) // add vary headers at any case. + origin, ok := c.extractOriginFunc(ctx) if !ok || !c.allowOriginFunc(ctx, origin) { c.errorHandler(ctx, ErrOriginNotAllowed)