Search code examples
javascriptajaxxmlhttprequest

Javascript: How can I force a POST request to treat the user as not authenticated


I'm using Javascript and XmlHttpRequest to POST to another URL on the same site. Users must be authenticated to access the page where the Javascript runs, but I need to submit the POST to the second URL as a non-authenticated user (to prevent the server from running code which is always run for authenticated users). Is there any way to submit the POST so that it appears to come from a non-authenticated user (so the server doesn't pull the user's authentication information from their session and treat them as authenticated for the POST)?

For example, is there a way to open a new session just for the POST, or to change the session ID just for the POST?

Note:

  • I tried to explicitly perform authorization using credentials for a non-existent user, but that didn't make any difference.
  • If this can be done using ajax instead of XmlHttpRequest, that's an acceptable solution.

Solution

  • Unfortunately this can not be achieved only in JavaScript, so you will have to make some changes on your server. You have two options:

    • Either you mark your session cookie as HttpOnly, so it won't be sent together with your request. But this will mean, that all your requests are sent as unauthenticated user.

    • Second option is use of a subdomain for this endpoint. Cookies are sent with XmlHttpRequests only on the same domain to prevent cross-site scripting. So if you move the server endpoint from www.example.com/myresource to api.example.com/myresource, the cookie will not be sent.