D
D
DarthJS2017-03-17 13:17:28
Yii
DarthJS, 2017-03-17 13:17:28

How to defeat OPTIONS on CORS?

That's the day I'm trying to win CORS.
There is a project that I turn on localhostand turn to from it REST
. The entire Internet has rustled, it seems that all the headers on both sides are correctly indicated ( Authorization Bearer), but it does not work.
When sending a request to the server, the first thing is sent OPTIONS(after which, as far as I understand from the documentation, it should follow POST, but this does not happen). OPTIONSsent, status 200and it has response. Now, if you reload the page, then POSTrequests are already sent.
Who knows the solutions to the problem?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Trakhimenok, 2017-03-17
@DarthJS

Just yesterday I figured it out for my debt tracking project https://debtstracker.io/ and won.
OPTIONS should return 200 with headers and an empty response.
I was guided by this scheme :
Here is my working Go code:

func getOnly(handler HttpHandler) HttpHandler {
  return func(w http.ResponseWriter, r *http.Request) {
    c := appengine.NewContext(r)
    if r.Method == "OPTIONS" {  // Preflight request
      origin := r.Header.Get("Origin")
      switch origin {
      case "http://localhost:8080":
      case "http://localhost:8100":
      case "https://debtstracker.local":
      case "https://debtstracker.io":
      case "":
        BadRequest(c, w, errors.New("Missing required request header: Origin"))
        return
      default:
        err := errors.New(fmt.Sprintf("Unknown origin: %v", origin))
        log.Debugf(c, err.Error())
        BadRequest(c, w, err)
        return
      }
      log.Debugf(c, "Request 'Origin' header: %v", origin)
      if accessControlRequestMethod := r.Header.Get("Access-Control-Request-Method"); accessControlRequestMethod != "GET" {
        BadRequest(c, w, errors.New("Not a valid preflight request"))
        return
      }
      responseHeader := w.Header()
      responseHeader.Set("Access-Control-Allow-Methods", "GET")
      if accessControlRequestHeaders := r.Header.Get("Access-Control-Request-Headers"); accessControlRequestHeaders != "" {
        log.Debugf(c, "Request Access-Control-Request-Headers: %v", accessControlRequestHeaders)
        responseHeader.Set("Access-Control-Allow-Headers", accessControlRequestHeaders)
      } else {
        log.Debugf(c, "Request header 'Access-Control-Allow-Headers' is empty or missing")
        // TODO(security): Is it wrong to return 200 in this case?
      }
      responseHeader.Set("Access-Control-Allow-Origin", origin)
      w.WriteHeader(200)
      return
    }
    if r.Method != "GET" {
      BadRequest(c, w, errors.New(fmt.Sprintf("Expecting to get request method GET, got: %v", r.Method)))
      return
    }
    handler(w, r)
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question