1
votes

I'm trying to setup a simple Ember.js app to talk with a custom API server, with JWT authentication. I can login at the API server and obtain a JWT token, but then no Authorization header is set in subsequent calls to the API server.

My login controller is:

import Ember from 'ember';
export default Ember.Controller.extend({

    actions: {
        authenticate: function() {
          var credentials = this.getProperties('identification', 'password'),
            authenticator = 'simple-auth-authenticator:jwt';

          this.get('session').authenticate(authenticator, credentials).then(function() {
              // authentication was successful
              console.log('OK');
            }, function(err) {
              // authentication failed
              console.log('FAIL ' + JSON.stringify(err));
            });

        },
        logOut: function() {
            this.get('session').invalidate();
        }
      }
});

I can successfully login and obtain a token. My login route:

import Ember from 'ember';

export default Ember.Route.extend({

    actions: {
         sessionAuthenticationFailed: function(error) {
            console.log('Login error: ' + error.ErrorDesc);
            this.controllerFor('login').set('loginErrorMessage', error.ErrorDesc);
            this.controllerFor('login').set('ErrorMoreInfo', error.MoreInfo);
        },

        sessionAuthenticationSucceeded: function() {
            console.log('Session authenticated: ' + this.get('session').content.secure.token);

            // redirect to last route requested, or to default route
            var attemptedTransition = this.get('session').get('attemptedTransition');
              if (attemptedTransition) {
                attemptedTransition.retry();
                this.get('session').set('attemptedTransition', null);
              } else {
                this.transitionTo('index');
              }
        }
    }
});

...shows me the token is properly acquired, and correctly redirects me to my protected routes (e.g. index). Since then, if I try to get any data from the API server, it does not receive any "Authorization: Bearer [token]" header at all. My environment configuration:

ENV['simple-auth'] = {
  authorizer: 'simple-auth-authorizer:token'
};
ENV['simple-auth-token'] = {
  refreshAccessTokens: true,
  timeFactor: 1000,
  refreshLeeway: 300, // Refresh the token 5 minutes (300s) before it expires.
  serverTokenEndpoint: 'https://localhost:8000/login',
  crossOriginWhitelist:[
     'http://localhost:4200',
     'https://localhost:8000'
    ],
  identificationField: 'user',
  passwordField: 'password',
  tokenPropertyName: 'token',
  authorizationPrefix: 'Bearer ',
  authorizationHeaderName: 'Authorization',
  // headers: {},
};

I also tried manually setting the header by calling jqXHR.setRequestHeader overriding the authorize function in my login route, but with no success:

    authorize: function(jqXHR, requestOptions) {
        var auth= "Bearer " + this.get('session').content.secure.Token;
        console.log('Add authorization header ' + auth);
        console.log( JSON.stringify(requestOptions));
        jqXHR.setRequestHeader("Authorization", auth);
    }

Can anybody tell what I'm missing? Shouldn't simple-auth-token take care of adding the header automatically? Thanks for any help, al.

2
I just discovered that the authorization token is sent if I work with a single host, i.e. if I put my ember app at locahost:8000 and keep the api server at locahost:8000/api. If I move ember to localhost:4200 (no matter the port nor the protocol) then the authorization token is not sent at all. It's not, afaik, a problem with CORS: the request for resources is sent to the server, all it misses is the authorization token. - Trapias
Did you ever figured this out? - Robbie Guilfoyle

2 Answers

1
votes

I had the same issue, with a REST adapter making calls on a different port.

Solved adding

    ENV['simple-auth'] = {
        crossOriginWhitelist: ['*']
    }
0
votes

Xabi's answer is working for me. But I didn't find it intuitive.

"Authorized requests" comply to a restrictive CORS policy : the authorization is not added in case of CORS issue.

In the docs :

Ember Simple Auth will never authorize requests going to a different origin than the one the Ember.js application was loaded from.

But requests that don't need an authorizer (with no 'Authorization' header in case of JWT) are allowed and working fine.