32

I have a angular app that I needed to redirect outside to a non angular html page, so I thought I could just use the $window.location.hrefto redirect the angular app to my external site. This actually works fine, however, I have a nodejs/express backend that checks for auth token before serving up any content(even static content).

This requires a auth token to be sent in the header of the http request. Now the question:

Can/How do you add an auth token to the request that is made by changing the $window.location.href before it is sent off?

Kevin Hakanson
  • 41,386
  • 23
  • 126
  • 155
britztopher
  • 1,214
  • 2
  • 16
  • 26

2 Answers2

38

When you use $window.location.href the browser is making the HTTP request and not your JavaScript code. Therefore, you cannot add a custom header like Authorization with your token value.

You could add a cookie via JavaScript and put your auth token there. The cookies will automatically be sent from the browser. However, you will want to review the security implications of using a cookie vs. a header. Since both are accessible via JavaScript, there is no additional attack vector there. Unless you remove the cookie after the new page loads, there may be a CSRF exploit available.

Kevin Hakanson
  • 41,386
  • 23
  • 126
  • 155
2

This answer is NOT a safe way, as the token is exposed in the URL, which is logged in browser history, access logs, etc. Use a domain cookie instead. I'll leave the answer as it can be an easy way to debug in your local setup.

I am using JWT as authentication on a Laravel PHP backend, and it works by putting ?token=... in the URL. For example, when using AngularJS with satellizer plug-in, I add ?token=' + $auth.getToken() to the URL.

Inserve
  • 1,796
  • 1
  • 12
  • 14
  • 10
    well embedding token as URL parameter is the last thing that i would like to do. – Ilker Baltaci May 19 '17 at 10:16
  • Even in SSL a sniffer could read the URL of the request so it is WORST way to pass a token to a request. If you're using SSL you should put the token in headers or in body. – Thecave3 Sep 12 '17 at 21:54
  • 3
    "in SSL a sniffer could read the URL of the request" This is not true, only the hostname/ip can be detected, not the url. – Laurens Feb 22 '18 at 09:21
  • Two vulnerabilities of doing this are: (1) The token is in the IIS logs (2) Drive by hacking, e.g. someone looks at your browser url or grabs it from your browser history while you make a cup of coffee – tony Aug 15 '19 at 08:08
  • This solution must be avoided for security reason as well explained by @tony – Luca Ritossa Dec 11 '19 at 08:22