c# - .net CORS - Losing Allow Origin header when the response is 401 - not authorized -
c# - .net CORS - Losing Allow Origin header when the response is 401 - not authorized -
i'm trying determine why/how i'm losing 'access-control-allow-origin' header when response 401-unauthorized.
i'm using token-based authentication token has expiration date.  when token expires, server returns 401-unauthorized, should, in chrome (and ie , ff) never sees allow origin header , errors usual cors error: xmlhttprequest cannot load http://my.rest.service. no 'access-control-allow-origin' header  nowadays on requested resource. origin 'http://localhost'  hence not allowed access.
i'm not sure of relevant though, auth logic works fine, cors chokes when response 401.
c# cors handlernamespace nviewrest.handlers {     using system.linq;     using system.net;     using system.net.http;     using system.threading;     using system.threading.tasks;      /// <summary>     /// handler processing cross origin resource sharing (cors) requests     /// </summary>     public class corshandler : delegatinghandler     {         /// <summary>the origin.</summary>         private const string origin = "origin";          /// <summary>header indicating should treat cors request.</summary>         private const string enablecors = "x-enablecors";          /// <summary>the access  command request method.</summary>         private const string accesscontrolrequestmethod = "access-control-request-method";          /// <summary>the access  command request headers.</summary>         private const string accesscontrolrequestheaders = "access-control-request-headers";          /// <summary>the access  command allow origin.</summary>         private const string accesscontrolalloworigin = "access-control-allow-origin";          /// <summary>the access  command allow methods.</summary>         private const string accesscontrolallowmethods = "access-control-allow-methods";          /// <summary>the access  command allow headers.</summary>         private const string accesscontrolallowheaders = "access-control-allow-headers";          /// <summary>         /// send async request         /// </summary>         /// <param name="request">the request.</param>         /// <param name="cancellationtoken">the cancellation token.</param>         /// <returns>the <see cref="task"/>.</returns>         protected override task<httpresponsemessage> sendasync(httprequestmessage request, cancellationtoken cancellationtoken)         {             // if has our nfib enable cors header or has access  command request method header, we're assuming cors request             var iscorsrequest = request.headers.contains(accesscontrolrequestmethod) || request.headers.contains(enablecors);              // preflight == options request - sent prior cors requests             var ispreflightrequest = request.method == httpmethod.options;              // express exit if normal request             if (!iscorsrequest)             {                  homecoming base.sendasync(request, cancellationtoken);             }              // actual cors request -  add together appropriate header before executing  normal             if (!ispreflightrequest)             {                   homecoming base.sendasync(request, cancellationtoken).continuewith(                     t =>                         {                             var resp = t.result;                             resp.headers.add(accesscontrolalloworigin, request.headers.getvalues(origin).first());                              homecoming resp;                         },                     cancellationtoken);             }              // @ point preflight request -  add together headers indicate allowed origins             var response = new httpresponsemessage(httpstatuscode.ok);             response.headers.add(accesscontrolalloworigin, request.headers.getvalues(origin).first());              //  add together header indicate allowed methods             var accesscontrolrequestmethod = request.headers.getvalues(accesscontrolrequestmethod).firstordefault();             if (accesscontrolrequestmethod != null)             {                 response.headers.add(accesscontrolallowmethods, accesscontrolrequestmethod);             }              //  add together headers indicate allowed headers             var requestedheaders = string.join(", ", request.headers.getvalues(accesscontrolrequestheaders));             if (!string.isnullorempty(requestedheaders))             {                 response.headers.add(accesscontrolallowheaders, requestedheaders);             }              // send result of options request             var tcs = new taskcompletionsource<httpresponsemessage>();             tcs.setresult(response);              homecoming tcs.task;         }     } }    i can step through lines add together header, when response 401, know on .net end adding it.
javascript ajax callfunction executeajax (method, url, data, token) {      url = (url.indexof('/') === 0) ? url : "/" + url;      var options = {         method: method,         url: app.settings.apiurlroot + url,         data:   info     };      token = token || localstorage.getitem("sessionkey");      options.headers = {         "accept": "application/json",          //header enabling cors         "x-enablecors": 'true'     }      if (token !== undefined && token !== null)     {         options.headers["x-adauth"] = token,     }       homecoming $.ajax(options); };    the result of phone call cors error referenced earlier.
there no issues firewall or middleware stripping these out know of since other non-401 ajax request executes fine.
any thoughts why header disappearing?
i had same issue , solved explicitly adding cors header 401 response before returned.
var response = new httpresponsemessage(httpstatuscode.unauthorized); response.headers.wwwauthenticate.add(new authenticationheadervalue("bearer", "errormessage")); response.headers.add(accesscontrolalloworigin, "*");  homecoming response;        c# ajax cors 
 
Comments
Post a Comment