CORS

If you are having trouble authenticating with your application from an SPA that executes on a separate subdomain, you have likely misconfigured your CORS (Cross-Origin Resource Sharing) or session cookie settings.

For more information on CORS and CORS headers, please consult the MDN web documentation on CORS.

You should ensure that your application's CORS configuration is returning the Access-Control-Allow-Credentials header with a value of true by setting the AllowCredentials option within your cors middleware configuration to true.

In addition, you should enable the withCredentials option on your global axios instance:

axios.defaults.withCredentials = true;

Using the CORS middleware

In this section you will learn how to use this middleware to allow cross-origin resource sharing.

The CORS middleware source code is located at iris-contrib/middleware repository.

1. Install the middleware:

$ go get github.com/iris-contrib/middleware/jwt@master

2. Import in your code:

import "github.com/iris-contrib/middleware/cors"

3. Initialize and configurate the middleware:

crs := cors.New(cors.Options{
    AllowedOrigins:   []string{"*"},
    AllowCredentials: true,
})

4. Register the middleware:

That's all. Your Iris web server can now accept cross-origin API requests from your client.

Example of a raw Javascript Client:

Full example code can be found at: iris-contrib/middleware/cors/_example.

The CORS Configuration

The full configuration of the cors.Options struct looks like this:

Do it yourself

You can always use the Iris request Context to manually send the necessary headers to handle preflight and therefore allow cross-origin requests.

Here is a simple example:

Last updated

Was this helpful?