Search code examples
javascriptfiwaredjango-cors-headers

CORS issue with Keyrock


I'm trying to integrate a custom application with Keyrock Fiware Identity Manager. The flow is the following:

  • The user clicks on LOGIN button
  • He is redirected to the

/oauth2/authorize/?response_type=code&client_id={clientid}&state=xyz&redirect_uri=http:{ip}:{port}

  • The user inserts his credentials
  • After the authentication he is redirected to my application where I try to retrieve the token as follow:

var reqData = "grant_type=authorization_code&code=" + code + "&redirect_uri=" + http:{ip}:{port};

var reqHeaders = new Object();
  reqHeaders.Access-Control-Allow-Headers= "Content-Type, Access-Control-Allow-Headers,Access-Control-Allow-Origin, Authorization, X-Requested-With, origin, accept",
  reqHeaders.Access-Control-Allow-Methods= "POST, GET, OPTIONS, DELETE, PUT",
  reqHeaders.Access-Control-Allow-Origin="*"
  reqHeaders.Access-Control-Expose-Headers="http://*/*"
  reqHeaders.Authorization="Basic {token}"
  reqHeaders.Content-Type="application/x-www-form-urlencoded"
  reqHeaders.X-Requested-With="XMLHttpRequest"

$.ajax({
      url : idmURL + '/oauth2/token',
      type : 'POST', 
      dataType : 'json',
      crossDomain : true,
      data : reqData,
      headers : reqHeaders,
      success : function(data) {
          console.log(data);
          token = data.access_token;
      }
});

But the post request never starts because I receive:

XMLHttpRequest cannot load http://{ip}:{port}/oauth2/token. Request header field Access-Control-Allow-Methods is not allowed by Access-Control-Allow-Headers in preflight response.

I've tried to insert the {ip}:{port} to the CORS_WHITELIST and to the ALLOWED_HOST in the local_settings.py file of Keyrock, but nothing changes.

Anyone can help me?


Solution

  • Ironically, I think the issue is caused by the fact that you're using the CORS headers meant for responses in your request:

    • Access-Control-Allow-Headers
    • Access-Control-Allow-Methods
    • Access-Control-Allow-Origin
    • Access-Control-Expose-Headers

    Thus the preflight fails because the server does not allow these, only a subset of headers as provided in the response header Access-Control-Allow-Headers.

    Remove these from the request.

    For more info: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS