0

I have Angular + Spring app and I trying to authenticate services with JWT tokens.

In Jwt authentication I am storing token in localStorage and attaching token in the Authorization HTTP header of a every request. This can be done by writing interceptor in AngularJs. I have followed this tutorial.

Now my question is:
How can I authenticate Requests made directly through hitting URL in browser ?

When you hit the Url at that time no page loaded and no script to bind URL from localStorage to Authentication header. so ultimately server will reject the request and send 401 even if the user is authenticated before.

pratik
  • 93
  • 1
  • 6
  • When heading directly to a URL, only cookies will provide a purely automated means of announcing that your client is authenticated. Could your server provide a custom 401/Unauthorized response, injected with the attempted URL, which pulls the JWT out of localStorage and makes the request? It's not the most efficient approach. – amoebob Jun 22 '16 at 12:52
  • I think I can not add header to the request which I hit in the browser. – pratik Jun 23 '16 at 09:45
  • Even if I manage to inject the attempted URL with 401 response and fetch the jwt out but after that.. how to add header to new page request (not ajax request)? I think its not possible as per [this](http://stackoverflow.com/questions/24130004/adding-http-headers-to-window-location-href-in-angular-app?answertab=active#tab-top) conversation. – pratik Jun 23 '16 at 09:51

1 Answers1

3

For web resources like videos, images or documents which need to be loaded directly by the browser, add to the url a parameter with JWT( you can not set headers)

  path/to/resource?jwt=...

At server side, decode the url looking for jwt if case of authentication header was not present

For incoming links that you have not generated, for example from a search engine,

  1) accept the link and redirect user to login page with a cookie/field set to the destination page
  2) automatically, login user with JWT from local storage set in header in the usual way
  3) if it is succesful, redirect to the destination 
pedrofb
  • 37,271
  • 5
  • 94
  • 142
  • As per your approach I think I have to write two conditions on server side 1) Check the jwt in header -> if it is present and valid -> user is authenticated 2) If not present in header -> check for url paramerter of jwt -> if it is present and valid -> user is authenticated.. am I correct? – pratik Jun 28 '16 at 05:29