erikringsmuth / app-router

Router for Web Components
https://erikringsmuth.github.io/app-router/
MIT License
610 stars 83 forks source link

send authentication header on route #117

Open Mipme opened 9 years ago

Mipme commented 9 years ago

I am trying to create a restricted area with the app-router. The router defaults to the login page and if i have a valid auth-token it let's me proceed to the other pages. That's working fine.

But how can i send the auth-token to the import destinations i have defined in my app-router setup?

<app-router id="router">
<!-- private routes requiring valid x-auth-token -->
  <app-route path="/" import="/api/home" element="api-home"></app-route>
  <app-route path="/settings" import="/api/settings" element="api-settings"></app-route>
<!-- public routes -->
  <app-route path="/login-page" import="/login-page"></app-route>
  <app-route path="*" import="/login-page"></app-route>
</app-router>

I have thought of the state-changed event, but could not find out if the app-router has any header property or function to utilize.

Any ideas appreciated!

erikringsmuth commented 9 years ago

Where do you get the auth-token to start? Is that checked in a state-changed event handler?

Mipme commented 9 years ago

On the /login-page i have an ajax-form calling /signin which returns the token. The token is saved in a global variable; an additional variable (loggedIn) is set to true. I've got an event listener on root like this:

document.addEventListener('polymer-ready', function() {
  var router = document.querySelector("#router");

  router.addEventListener('before-data-binding', function(e) {
    var g = document.querySelector('#globals');
    if (!g.loggedIn && e.detail.path != '/login-page') {
      e.preventDefault();
      router.go('/login-page', {replace: true});
    }
  });
});

Under g.token i can access the token...

The reason why i chose the 'before-data-binding' event was that it is the only one firing up when the page is loaded initially. 'state-changed' is only firing when the page path changes...

erikringsmuth commented 9 years ago

Is there an ajax call to populate the globals element? You could manually initialize the router after the globals element has been populated. https://erikringsmuth.github.io/app-router/#/api#init

Mipme commented 9 years ago

Sorry - been quite busy these days. I had a look at the code and guess it's not really possible to send an Auth Header with the app-route because the component simply creates and import tag and does not make an XHR/Ajax call or anything similar.

For the moment i got around it, because it is actually not required. Now i simply load page templates without authentification and populate it with private data from Ajax calls – which support sending header data. So, by design, i got rid of the problem. But i don't know if this approach is universal and can be recommended in general...

Still, thanks for looking into this problem!