DelphiLynx
DelphiLynx

Reputation: 921

Ember.js Ember Simple Auth persist authentication information in LocalStorage does not work

I use Ember Simple Auth with the following settings: Note: I use Ember App Kit.

app.js

// init Ember.SimpleAuth
App.initializer({
    name: 'authentication',
    initialize: function(container, application) {
        Ember.SimpleAuth.setup(application, { // @todo at version 0.1.2 of Ember-simple-auth, add container variable
            crossOriginWhitelist: ['http://customdomain'], 
            // store: Ember.SimpleAuth.Stores.LocalStorage, // default now
            authenticationRoute: 'article.login'
        });
    }
});

export
default App;

a simple loginController (took it mostly from Ember App Kit Simple Auth)

var CustomAuthenticator = Ember.SimpleAuth.Authenticators.OAuth2.extend({
    serverTokenEndpoint: 'http://customdomain/access_token/',

    makeRequest: function(data) {
        return Ember.$.ajax({
            url: this.serverTokenEndpoint,
            type: 'POST',
            data: {
                grant_type: 'password',
                username: data.username,
                password: data.password
            },
            dataType: 'json',
            contentType: 'application/x-www-form-urlencoded'
        });
    }
});

var LoginController = Ember.Controller.extend(Ember.SimpleAuth.LoginControllerMixin, {
    authenticator: CustomAuthenticator,

    actions: {
        // display an error when logging in fails
        sessionAuthenticationFailed: function(message) {
          console.log('sessionAuthenticationFailed');
            this.set('errorMessage', message);
        },

        // handle login success
        sessionAuthenticationSucceeded: function() {
          console.log('sessionAuthenticationSucceeded');

            this.set('errorMessage', "");
            this.set('identification', "");
            this.set('password', "");
            this._super();
        }
    }
});

export
default LoginController;

So far so good, I can authenticate a user thought a login form. However when I press F5, I have to login again. The LocalStorage adapter is empty. So the question is what do I need to persist the token and session?

Note: I cannot update to ember-simple-auth 0.1.2, bower cannot find the new version. Seems that the github version of https://github.com/simplabs/ember-simple-auth-component is not up to date.

Edit: I have updated my code as follows:

app.js

// init Ember.SimpleAuth
App.initializer({
    name: 'authentication',
    initialize: function(container, application) {
        Ember.SimpleAuth.Authenticators.OAuth2.reopen({
            serverTokenEndpoint: 'http://customdomain/access_token'
        });

        Ember.SimpleAuth.setup(container, application, { // @todo at version 0.1.2 of Ember-simple-auth, add container
            crossOriginWhitelist: ['http://customdomain'], // @todo remove when live
            // store: Ember.SimpleAuth.Stores.LocalStorage,
            authenticationRoute: 'article.login'
        });
    }
});

export default App;

loginController:

var LoginController = Ember.Controller.extend(Ember.SimpleAuth.LoginControllerMixin, {
    // authenticator: CustomAuthenticator, // not needed anymore

    actions: {
        // display an error when logging in fails
        sessionAuthenticationFailed: function(message) {
            this.set('errorMessage', message);
        },

        // handle login success
        sessionAuthenticationSucceeded: function() {
            this.set('errorMessage', "");
            this.set('identification', "");
            this.set('password', "");
            this._super();
        }
    }
});

export default LoginController;

Upvotes: 2

Views: 2364

Answers (2)

marcoow
marcoow

Reputation: 4062

This should be fixed with 0.1.2: github.com/simplabs/ember-simple-auth/releases/tag/0.1.2

I also just updated github.com/simplabs/ember-simple-auth-component

Upvotes: 2

Sarus
Sarus

Reputation: 3313

I haven't used the oauth2 authenticator before (just a custom one for my backend that I wrote) but I think the same concepts should apply.

When you refresh the page ember-simple-auth makes a call to the restore method of the oauth2 authenticator that you are using. The restore method is looking for a property called 'access_token' to confirm that the user has already authenticated with your server. Does your REST API return a property called access_token when you authenticate with the endpoint at http://customdomain/access_token/? If not, you want to make sure this is happening or you will encounter the refresh issue you're having. Here's the restore method in the oauth2 authenticator provided with ember-simple auth:

restore: function(properties) {
    var _this = this;
    return new Ember.RSVP.Promise(function(resolve, reject) {
      // It looks for the 'access_token' property here which should have been set
      // by the authenticate method if you returned it from your REST API
      if (!Ember.isEmpty(properties.access_token)) { 
        _this.scheduleAccessTokenRefresh(properties.expires_in, 
                      properties.expires_at, 
                      properties.refresh_token);
        resolve(properties);
      } else {
        reject();
      }
    });
  }

Additionally, I think in your sessionAuthenticationSucceeded action you need to return true. Otherwise the action won't propagate up to the ember-simple-auth ApplicationRouteMixin (unless you are not using that mixin or don't depend on its sessionAuthenticationSucceeded method in which case it doesn't matter).

Upvotes: 3

Related Questions