PolymerElements / iron-ajax

Easily make ajax requests
https://www.webcomponents.org/element/PolymerElements/iron-ajax
127 stars 113 forks source link

Add JWT token to headers for every request #209

Closed wilmveel closed 8 years ago

wilmveel commented 8 years ago

For a project we have to send a JWT token in the header for every ajax request to the API. What is the best practice for iron-ajax to decorate ajax calls with extra headers?

CaptainCodeman commented 8 years ago

Hi @wilmveel

I've reached the same point in my Polymer experience ... what I'm doing is extending <iron-ajax> so I end up with my own <auth-ajax> element which has the exact same API but will handle adding the JWT access token and performing any token refresh when necessary.

This hooks into other elements modelled off <google-signin> to handle the interaction with the auth server, signing in, auth status, connecting oauth accounts and so on (where JWT tokens are issued by my own auth server so I can include roles and other things).

It seems to be working well enough and the right approach as far as I can tell.

e111077 commented 8 years ago

If it is possible for you to assign the token to a value, a way this can be to use a computed property for the header so that you can simply set the values using the properties of the custom element.

<iron-ajax
  url=...
  params=...
  headers="[[headers]]">
</iron-ajax>

<script>
Polymer({
  is: ...,

  properties: {
    alg: {
      type: String,
      val: ''
    },

    typ: {
      type: String,
      val: ''
    },

    headers: {
      type: Object,
      computed: '_computeHeaders(alg,typ,otherVariablesThatChange)'
    }
  },

  _computeHeaders: function (alg, typ, otherVariablesThatChange) {
    var outputHeaders = {};
    outputHeaders.staticHeader = 'whatever value this needs to be';
    if (alg && typ) {
      outputHeaders.alg = alg;
      outputHeaders.typ = typ;
    }
    return outputHeaders;
  }
});
</script>

Also, you can also use an observer:

<iron-ajax
  id="ajax"
  url=...
  params=...
  headers="[[headers]]">
</iron-ajax>

<script>
Polymer({
  is: ...,

  properties: {
    alg: {
      type: String,
      val: ''
    },

    typ: {
      type: String,
      val: ''
    },

    headers: {
      type: Object
    }
  },

  observers: ['_generateHeadersAndRequest(alg, typ, otherVariablesThatChange)'],

  _generateHeadersAndRequest: function (alg, typ, otherVariablesThatChange) {
    var outputHeaders = {};
    outputHeaders.staticHeader = 'whatever value this needs to be';
    if (alg && typ) {
      outputHeaders.alg = alg;
      outputHeaders.typ = typ;
    }

    this.headers = outputHeaders;
    this.$.ajax.generateRequest();
  }
});
</script>

If you have any other questions like this, I highly recommend that you ask them on our Slack channel! There are lots of other committed developers on there and they will probably get to you faster than a github issue.