0

sorry for that (maybe) silly question. Im super new to this topic!

I created a custom authorizer:

    import Ember from 'ember';
    import Base from 'ember-simple-auth/authorizers/base';
    export default Base.extend({
        authorize: function(jqXHR, requestOptions) {
            var accessToken = this.get('session.content.secure.token');
            if (this.get('session.isAuthenticated') && !Ember.isEmpty(accessToken)) {
                jqXHR.setRequestHeader('Authorization', 'Bearer ' + accessToken);
            }
        }
    });

And now i want to include the token in a ajax request in my controller (this is my code without the token send):

// app/controllers/workouts.js
import Ember from 'ember';
import config from '../config/environment';

export default Ember.Controller.extend({
  requestEndpoint: config.ServerIp+'/workouts',
  workouts: function() {
        Ember.$.ajax({
            type: "GET",
            url: requestEndpoint
        }).success(function(data) {
            return data;
        })
  }.property()
});

Thank you very much for helping and understanding this great module!

orgertot
  • 197
  • 16

1 Answers1

1

You could have something like this.

In your authorizer:

// app/authorizers/your-authorizer.js
import BaseAuthorizer from 'ember-simple-auth/authorizers/base';

export default BaseAuthorizer.extend({
    authorize(data, block) {
        const accessToken = data.accessToken; //Data is the response returned by the server
        if (!Ember.isEmpty(accessToken)) {
            block('Authorization', `Bearer ${accessToken}`);
        }
    }
});

The adapter will take care of adding the authorization header to all your requests:

// app/adapters/application.js
import DS from 'ember-data';
import DataAdapterMixin from 'ember-simple-auth/mixins/data-adapter-mixin';

export default DS.JSONAPIAdapter.extend(DataAdapterMixin, {
    authorizer: 'authorizer:your-authorizer'
});

If you are not using ember data, you can take a look the way this mixin works to create your own adapter: data-adapter-mixin

To protect your route from access if the users are not logged, you need to add the authenticated mixin:

// app/routes/home.js
import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin';

export default Route.extend(AuthenticatedRouteMixin, {
    ...
});

And don't forget to set some configuration

// config/environment.js
...
var ENV = {
    ...
    'ember-simple-auth': {
        authenticationRoute: 'login',
        routeAfterAuthentication: 'home',
        routeIfAlreadyAuthenticated: 'home'
    }
}
alexmngn
  • 9,107
  • 19
  • 70
  • 130