Friday 14 February 2020

Cross-Origin Resource Sharing (CORS) support for Gin

[gin](https://github.com/gin-gonic/gin) is a popular HTTP web framework written in Go. I've worked with a few people using it to build restful APIs. When the frontend side sends an Ajax request to their backend endpoint from my localhost, it shows the following error message: ``` Access to XMLHttpRequest at 'http:///?_=1575637880588' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. ``` This security risk is only considered by webkit based browsers like Chrome or Safari and they block ajax queries. If you use Firefox, you can get rid of it. If Chrome is your only browser, you use start with your Chrome with the ``--disable-web-security`` flag. As the resources are requested by Ajax, it by default forbids same-origin security policy. That means the resources you request and the first page you access must be in the same origin. The fix is pretty simple and it is quite clear to state that No 'Access-Control-Allow-Origin' header is present on the requested resource. In gin's world, we just need to add a middleware. ``` go get github.com/gin-contrib/cors ``` ``` import "github.com/gin-contrib/cors" ``` You may use the ``DefaultConfig`` as a starting point. By default, no origin is allowed for GET, POST, PUT and HEAD methods. Credentials share is disabled the preflight requests is cached for 12 hours. ``` func main() { router := gin.Default() config := cors.DefaultConfig() config.AllowOrigins = []string{"http://foo.com"} router.Use(cors.New(config)) router.Run() } ``` It can also allow all origins, which I personally don't recommend as you should create a whitelist to indicates which origins are allowed for best practice. ``` func main() { router := gin.Default() router.Use(cors.Default()) router.Run() } ```

No comments:

Post a Comment

A Fun Problem - Math

# Problem Statement JATC's math teacher always gives the class some interesting math problems so that they don't get bored. Today t...