Tobi696
Tobi696

Reputation: 458

Custom http Header breaks CORS

My API has following CORS setup:
(I am the owner, I can change these settings)

Middleware function:

// HeaderMiddleware ...
func HeaderMiddleware(next httprouter.Handle) httprouter.Handle {
    return httprouter.Handle(func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
        w.Header().Set("Content-Type", "application/json")
        w.Header().Set("Access-Control-Allow-Origin", "*")
        w.Header().Set("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, X-APIKEY")
        // ! Production
        // if r.Header.Get("X-APIKEY") != "fdfdsf5df6d541cd6" || r.RemoteAddr != frontendURL {
        //  w.WriteHeader(http.StatusForbidden)
        //  json.NewEncoder(w).Encode(NoContentResponse{Success: false, Error: "You aren't allowed to request the api here."})
        //  return
        // }
        // ! Production

        next(w, r, p)
    })
}

The X-APIKEY header is not necessary yet, a request without it just works fine:

fetch('http://localhost:8013/[email protected]/usage', { headers: { } })
.then(response => response.json())
.then(console.log)

returns {used: false} (expected response)

However, if I add the X-APIKEY header:

fetch('http://localhost:8013/[email protected]/usage', { headers: { 'X-APIKEY': 'sdfsdfsafsf' } })
.then(response => response.json())
.then(console.log)

following error is thrown:
Access to fetch at 'http://localhost:8013/[email protected]/usage' from origin 'http://localhost:8080' 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. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

If I do the request with the X-APIKEY header in Postman, it says that the Access-Control-Allow-Origin header is sent along: Postman says the header is sent along

P.S.: I already tried other headers, it works! If I do the request with chrome (without X-APIKEY header), the Access-Control-Allow-Origin header is sent.

Thanks for your help!

Upvotes: 0

Views: 939

Answers (1)

Tobi696
Tobi696

Reputation: 458

I've now fixed it like this:
I misuse the http Accept header for my API-Token.

Example:

fetch('http://10.0.0.11:8013/lopm@htl/usage',
{"headers":{ "Accept": "fdfdsf5df6d541cd6++" }})
.then(response => response.json())
.then(console.log)


Of course, this isn't a really nice solution, but it does its job.

Thanks for all of you for giving me helpful tips!

Upvotes: 1

Related Questions