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:
1
axios.defaults.withCredentials = true;
Copied!

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:
1
$ go get github.com/iris-contrib/middleware/[email protected]
Copied!
2. Import in your code:
1
import "github.com/iris-contrib/middleware/cors"
Copied!
3. Initialize and configurate the middleware:
1
crs := cors.New(cors.Options{
2
AllowedOrigins: []string{"*"},
3
AllowCredentials: true,
4
})
Copied!
4. Register the middleware:
1
app.UseRouter(crs)
Copied!
That's all. Your Iris web server can now accept cross-origin API requests from your client.
Example of a raw Javascript Client:
1
// Replace the "host" with your Iris web server's domain.
2
const host = 'https://e1de7bc1.ngrok.io';
3
4
async function postData(url = '', data = {}) {
5
const response = await fetch(url, {
6
method: 'POST',
7
mode: 'cors',
8
cache: 'no-cache',
9
credentials: 'same-origin',
10
headers: {
11
'Content-Type': 'application/json'
12
},
13
redirect: 'follow',
14
referrerPolicy: 'no-referrer',
15
body: JSON.stringify(data)
16
});
17
return response.json();
18
}
19
20
postData(host + '/api/mailer', {
21
22
})
23
.then(data => {
24
console.log(data);
25
document.write(data.message);
26
});
Copied!
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:
1
// AllowedOrigins is a list of origins a cross-domain
2
// request can be executed from.
3
// If the special "*" value is present in the list,
4
// all origins will be allowed.
5
// An origin may contain a wildcard (*) to replace 0
6
// or more characters (i.e.: http://*.domain.com).
7
// Usage of wildcards implies a small performance penalty.
8
// Only one wildcard can be used per origin.
9
// Default value is ["*"].
10
AllowedOrigins []string
11
12
// AllowOriginFunc is a custom function to validate the origin.
13
// It takes the origin as argument and returns true if allowed
14
// or false otherwise. If this option is
15
// set, the content of AllowedOrigins is ignored.
16
AllowOriginFunc func(origin string) bool
17
18
// AllowedMethods is a list of methods the
19
// client is allowed to use with cross-domain requests.
20
// Default value is simple methods (HEAD, GET and POST).
21
AllowedMethods []string
22
23
// AllowedHeaders is list of non simple headers
24
// the client is allowed to use with
25
// cross-domain requests.
26
// If the special "*" value is present in the list,
27
// all headers will be allowed.
28
// Default value is [] but "Origin" is always
29
// appended to the list.
30
AllowedHeaders []string
31
32
// ExposedHeaders indicates which headers are safe to
33
// expose to the API of a CORS API specification.
34
ExposedHeaders []string
35
36
// MaxAge indicates how long (in seconds) the results
37
// of a preflight request can be cached.
38
MaxAge int
39
40
// AllowCredentials indicates whether the request
41
// can include user credentials like
42
// cookies, HTTP authentication
43
// or client side SSL certificates.
44
AllowCredentials bool
45
46
// OptionsPassthrough instructs preflight to
47
// let other potential next handlers to
48
// process the OPTIONS method. Turn this on
49
// if your application handles OPTIONS.
50
OptionsPassthrough bool
51
52
// Debugging flag adds additional output to
53
// debug server side CORS issues.
54
Debug bool
Copied!

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:
1
package main
2
3
import "github.com/kataras/iris/v12"
4
5
func main() {
6
app := iris.New()
7
8
// Our custom CORS middleware.
9
crs := func(ctx iris.Context) {
10
ctx.Header("Access-Control-Allow-Origin", "*")
11
ctx.Header("Access-Control-Allow-Credentials", "true")
12
13
if ctx.Method() == iris.MethodOptions {
14
ctx.Header("Access-Control-Methods",
15
"POST, PUT, PATCH, DELETE")
16
17
ctx.Header("Access-Control-Allow-Headers",
18
"Access-Control-Allow-Origin,Content-Type")
19
20
ctx.Header("Access-Control-Max-Age",
21
"86400")
22
23
ctx.StatusCode(iris.StatusNoContent)
24
return
25
}
26
27
ctx.Next()
28
}
29
30
app.UseRouter(crs)
31
32
// [register routes...]
33
}
Copied!
Last modified 1yr ago