0

I'm using the new version of ember-simple-auth, which doesn't automatically anymore add access token to ajax requests that are sent to the server.

I'm using oauth2 authentication, and due to a bad documentation I somehow cannot figure out what and where it would be the right way to set the header token for each ajax request that I do.

Should this code be under the authorize function of the custom authorizer or somewhere else?

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

Any information on setting up this correctly would be highly appreciated!

all jazz
  • 2,007
  • 2
  • 21
  • 37

2 Answers2

1

You could do it like this:

let userToken;
this.get('session').authorize('authorizer:some-authorizer', (headerName, headerValue) => {
    userToken = headerValue;
});

$.ajax({
    url: "Your Url",
    // ...
    beforeSend: function(xhr){
        xhr.setRequestHeader('Authorization', userToken);
    }
})

If you don't want to do that on every request, you could create your own customAjaxCall somewhere and just use that one:

export default function customAjaxCall(session, url) {
    let userToken;
    session.authorize('authorizer:some-authorizer', (headerName, headerValue) => {
        userToken = headerValue;
    });

    return $.ajax({
        url: url,
        dataType: 'json',
        contentType: 'application/json; charset=UTF-8',
        // ...
        beforeSend: function(xhr){
            xhr.setRequestHeader('Authorization', userToken);
        }
    })
}
Remi Smirra
  • 2,499
  • 1
  • 14
  • 15
1

We use a custom adapter in our application the adapter looks something like this

import DS from "ember-data";
import Ember from "ember";
import App from '../app';

export
default DS.RESTAdapter.extend({
    namespace: 'data',
    host: App.hostUrl,
    ajax: function (url, type, hash) {
        hash = hash || {};
        hash.headers = hash.headers || {};
        hash.headers['Authorization'] = 'Token token=' + App.access_token;
        hash.crossDomain = true;
        return this._super(url, type, hash);
    }
});

Every other model adapter used extends this adapter for ex.

import ApplicationAdaper from './application';

export default ApplicationAdaper.extend({
   ...
});

For reference and further Information Check RESTAdapter Header Customization http://emberjs.com/api/data/classes/DS.RESTAdapter.html