Echo CORS w/ Proxy middlewares causes problems w/ Access-Allow-Origins response header - go

I'm using LabStack's Golang Echo Framework to build out a service.
One of the routes, needs to proxy requests and responses to and from a backend service.
But I also need CORS to work on this service as well.
So I'm using middleware.CORSWithConfig along w/ a middleware.ProxyWithConfig in my request/response stack.
I'm seeing some oddness w/ the Access-Control-Allow-Origins header where the value for that header on the response from the proxied service to my Echo server *, but once it passes through the proxy, it changes to *, * by the time it gets back into the client.
Upon which I start seeing the following browser errors related to CORS violations:
VM1627:362 Access to XMLHttpRequest at 'http://localhost:6273/' from origin 'http://localhost:8002' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header contains multiple values '*, *', but only one is allowed.
Has anyone come across this? Anyone have any idea why this might be happening and maybe a way around it?
Here's some example code:
package main
func singleTargetBalancer(url *url.URL) middleware.ProxyBalancer {
targetURL := []*middleware.ProxyTarget{
{
URL: url,
},
}
return middleware.NewRoundRobinBalancer(targetURL)
}
func Noop(ctx echo.Context) (err error) {
ctx.String(
http.StatusNotImplemented,
"No op handler should never be reached!",
)
return err
}
func main() {
e := echo.New()
e.HideBanner = true
e.Use(
middleware.CORSWithConfig(middlewares.CustomCorsConfig),
middlewares.ThriftMetrics(),
)
// Have to use a Noop handler since we're not trying to set up a full-on proxy for the backend service. We only want this one route to be proxied.
e.POST(
"/",
handlers.Noop,
middleware.ProxyWithConfig(middleware.ProxyConfig{
Balancer: singleTargetBalancer("[backend service URL]"),
})
)
}

I ultimately solved this by writing a custom Echo middleware to hook into the response before Echo's proxy middleware could send the headers back to the client.
func setResponseACAOHeaderFromRequest (req http.Request, resp echo.Response) {
resp.Header().Set(echo.HeaderAccessControlAllowOrigin,
req.Header.Get(echo.HeaderOrigin))
}
func ACAOHeaderOverwriteMiddleware(next echo.HandlerFunc) echo.HandlerFunc {
return func(ctx echo.Context) error {
ctx.Response().Before(func() {
setResponseACAOHeaderFromRequest(*ctx.Request(), *ctx.Response())
})
return next(ctx)
}
}
Then just put this middleware in e.Use() right before your proxy middleware:
e.POST(
"/",
handlers.Noop,
ACAOHeaderOverwriteMiddleware,
middleware.ProxyWithConfig(middleware.ProxyConfig{
Balancer: singleTargetBalancer("[backend service URL]"),
})
)
Docs for Echo's Request::Before() hook: https://echo.labstack.com/guide/response#before-response

Related

how to pass parameter of the destination to middleware in gin/golang

My problem in short is:
I send my auth token as a parameter to my destination api and it seems like middleware can not access that. How can I access the parameter since the middleware needs that to check the auth conditions?
I am trying to implement a simple authentication/authorization application.
I know that it is common to set auth token in coockies, however, in my use-case, I need it to be implemented differently.
The implementation is: login returns auth token in response body and anytime authentication token is required, it is sent as a parameter "authorization" to the application.
here is the code for my user routers :
func UserRoute(router *gin.Engine) {
user := router.Group("/user")
{
user.POST("/signup", controllers.SignUp)
user.POST("/login", controllers.Login)
user.GET("/validate", middleware.RequireAuth, controllers.Validate)
}
}
validate function in usercontrollers.go:
func Validate(c *gin.Context) {
user, _ := c.Get("user")
c.IndentedJSON(http.StatusOK, gin.H{
"message": user,
})
}
here is the request I send
http://localhost:6000/user/validate?authorization=[My-JWT-Token]
Now when I try to read my auth parameter and use it in my middleware it seems like it does not actually exist:
func RequireAuth(c *gin.Context) {
confs, _ := configs.LoadConfig()
tokenString := c.Param("authorization")
if tokenString == "" {
// this abort case always happens
c.AbortWithStatus(http.StatusUnauthorized)
}
}
1. ctx.Request.URL.Query().Get("authorization")
2. ctx.Query("authorization")

307 redirect with Authorization header

In looking at the Go docs for http it looks like the Authorization header is removed when a response is a 307. Obviously it makes sense for almost every case but is there a way not to remove the Authorization header?
You can modify your http.Client to add the header again after it has been removed using CheckRedirect:
CheckRedirect func(req *Request, via []*Request) error
Since req is the upcoming request, it can be modified before it is sent. After making the changes, return nil to indicate that the request should still be sent.
Since this is a change to the http client instead of the request, you should check that this redirect is only used for the one URL where you need it (in case you use that client to do other requests).
You client definition could look like this:
http.Client{
CheckRedirect: func(req *http.Request, via []*http.Request) error {
// you can check old responses for a status code
if len(via) != 0 && via[0].Response.StatusCode == http.StatusTemporaryRedirect {
req.Header.Add("Authorization", "some-value")
}
return nil
},
}

how to proxy GET request in golang with URL manipulation

I want to build a golang service which will listen for GET request, do some URL manipulation and then proxy a new request (to the manipulated URL) back to the browser:
(from browser -> server) GET http://www.example.com/7fbsjfhfh93hdkwhfbf398fhkef93..
(server manipulates URL - decrypts "7fbsjfhfh93hdkwhfbf398fhkef93.." -> "my-super-resource")
(server -> URL resource) GET http://www.somewhereelse.com/my-super-resource
(server -> browser) Response from http://www.somewhereelse.com/my-super-resource passed on to browser (using cors)
The whole chain will need to be synchronous which is ok. Is there a decent proxy library which allows for this sort of thing?
You can do something like this in less than 10 lines of code with the Sling package:
type Foo struct {
Bar string `json:"bar"`
}
func Handler(w http.ResponseWriter, r *http.Request) {
// Get the URL and decrypt it
url := getUrl(r)
decryptedUrl := decryptUrl(url)
// Use the decrypted URL to make a request to another service
var data *Foo
req, err := sling.New().Get(decryptedUrl).Receive(data)
if err != nil {
// Handle error...
}
// Respond to the original request using the data from the other service
respond(w, http.StatusOK, data)
}

axios does not send POST to golang api

I have a golang api backend with a negroni middleware.
I already implemented the CORS handler for negroni, so my api should allow cross origin resource sharing.
// allow OPTIONS method of CORS requests
c := cors.New(cors.Options{
AllowedOrigins: []string{"http://127.0.0.1"},
})
//common.StartUp() - Replaced with init method
// Get the mux router object
router := routers.InitRoutes()
// Create a negroni instance
n := negroni.Classic()
n.Use(c)
n.UseHandler(router)
server := &http.Server{
Addr: common.AppConfig.Server,
Handler: n,
}
log.Println("Listening...")
server.ListenAndServe()
This is from the https://github.com/rs/cors/blob/master/examples/negroni/server.go example of implementing CORS with negroni.
Nevertheless my api now responses a 200 status back to my frontend, but the frontend does not send the POST request to the server. This my axios code:
import axios from 'axios';
const data = {
email: 'user#mail.com',
password: 'secret',
};
export default {
name: 'Login',
methods: {
login() {
axios.post('https://127.0.0.1:8090/users/login', data);
},
Postman does not have any problems with sending the POST request. What am I doing wrong?
Okay I found a solution for the problem:
As described in this article, I added some more options to the cors negroni plugin. One important option that was missing in my application was the line
AllowedHeaders: []string{"X-Auth-Key", "X-Auth-Secret", "Content-Type"},
Because my app sent the Content-Type Header and the api refused it.
I hope this will help others with similar problems.

Serving a websocket in Go

I'm starting to play around with websockets + go and well I think I'm misunderstanding something quite basic with websockets in Go.
I'd like to simply listen for a websocket connection and process accordingly. However all examples I see in Go using websocket is serving the web page that then connects to the websocket, is this a requirement?
The following is a basic echo server I have setup:
package main
import (
"fmt"
"code.google.com/p/go.net/websocket"
"net/http"
)
func webHandler(ws *websocket.Conn) {
var s string
fmt.Fscan(ws, &s)
fmt.Println("Received: ", s)
}
func main() {
fmt.Println("Starting websock server: ")
http.Handle("/echo", websocket.Handler(webHandler))
err := http.ListenAndServe(":8080", nil)
if err != nil {
panic("ListenAndServe: " + err.Error())
}
}
This is the javascript used to connect:
ws = new WebSocket("ws://localhost:8080/echo");
ws.onmessage = function(e) {
console.log("websock: " + e.data);
};
However this results in:
WebSocket connection to 'ws://localhost:8080/echo' failed: Unexpected response code: 403
When working with websockets from Javascript, you will seldom have to read the frames directly. To be honest, I am not even sure how to do that.
Fortunately, the websocket package already has a type, Codec that does this for you. My suggestion is to use the predefined websocket.Message codec to Recieve and Send messages instead.
Message is a codec to send/receive text/binary data in a frame on WebSocket connection. To send/receive text frame, use string type. To send/receive binary frame, use []byte type.
Using websocket.Message, your webHandler would look something like this:
func webHandler(ws *websocket.Conn) {
var in []byte
if err := websocket.Message.Receive(ws, &in); err != nil {
return
}
fmt.Printf("Received: %s\n", string(in))
websocket.Message.Send(ws, in)
}
And, no, it is not a requirement that Go serves the webpage. The 403 error you received does not have to do with Go or the websocket package.
I had a similar issue and the 403 error problem is related to how Go treats the http Origin header:
Handler is a simple interface to a WebSocket browser client. It checks if Origin header is valid URL by default. You might want to verify websocket.Conn.Config().Origin in the func. If you use Server instead of Handler, you could call websocket.Origin and check the origin in your Handshake func. So, if you want to accept non-browser client, which doesn't send Origin header, you could use Server . that doesn't check origin in its Handshake.
In order to disable the Origin check, you must use something like:
http.HandleFunc("/echo",
func (w http.ResponseWriter, req *http.Request) {
s := websocket.Server{Handler: websocket.Handler(webHandler)}
s.ServeHTTP(w, req)
});
At least that solved the issue for me (server to server WebSocket communication) and I think it could solve the problem as well if the origin header does not match.

Resources