Search code examples
ember-simple-auth

Ember Simple Auth: How to set/send multiple request headers?


I've burned quite a bit of time trying to figure this one out.

My backend is Rails 4.x with devise_token_auth

To authorize a request after login, I need to send multiple headers with each request, like this (verified working with curl):

curl -X GET -H "Content-Type: application/vnd.api+json" -H "Access-Token: 33YPWz2Kr4eMimYjblDg7w" -H "Client: godv0EDuuc-2qZ6kvrVLzQ" -H "Token-Type: Bearer" -H "Accept: application/vnd.api+json" -H "Uid: example@gmail.com" -H "Expiry: 1459295877" -H "Provider: Email"  "http://localhost:3000/api/v1/forms"

I'm utterly lost as to how the authorize api actually works. I don't see how I can set more than one request header within the DeviseAuthorizer#authorize method.

If someone knows how to do this and can answer the question, I will immediately open a pull request to fix the Ember Simple Auth documentation in this area.


Solution

  • The devise authorizer passes a function as the 2nd argument to #authorize.


    http://ember-simple-auth.com/api/classes/BaseAuthorizer.html#method_authorize

    authorize(data, block(headerName,headerContent))
    

    Arguments

    data: Object The data that the session currently holds

    block(headerName,headerContent): Function The callback to call with the authorization data; will receive the header name and header content as arguments


    If you want to add your own headers, you can create your authorizer class extending from the devise authorizer. Then override the authorize method like this:

    import Ember from 'ember';
    import Devise from 'ember-simple-auth/authorizers/devise';
    
    export default Devise.extend({
      authorize(data, header) {
        this._super(data, header);
    
        header('X-Custom-Header', "The custom 1 header");
        header('X-Other-Custom-Header', "The custom 2 header");
      }
    });
    

    This works because in the data adapter mixin, it is passing this function:

    this.get('session').authorize(authorizer, (headerName, headerValue) => {
        xhr.setRequestHeader(headerName, headerValue);
    });