ember-simple-auth + oauth2 : session lost on refresh

164 Views Asked by At

I read that session restore is supposed to work out of the box, but it doesn't for me, and I can't find what I did wrong.

authenticators/oauth2.js :

import OAuth2PasswordGrant from 'ember-simple-auth/authenticators/oauth2-password-grant';

export default OAuth2PasswordGrant.extend({
    serverTokenEndpoint: '/oauth/token'
});

routes/application.js :

import Route from '@ember/routing/route';
import { inject as service } from '@ember/service';
import ApplicationRouteMixin from 'ember-simple-auth/mixins/application-route-mixin';

export default Route.extend(ApplicationRouteMixin, {
    currentUser: service(),

    beforeModel() {
        return this._loadCurrentUser();
    },

    sessionAuthenticated() {
        this._super(...arguments);
        this._loadCurrentUser();
    },

    _loadCurrentUser() {
        return this.get('currentUser').load().catch(() => this.get('session').invalidate());
    }
});

services/current-user.js :

import Service from '@ember/service';
import { inject as service } from '@ember/service';
import RSVP from 'rsvp';

export default Service.extend({
    session: service('session'),
    store: service(),

    load() {
        if (this.get('session.isAuthenticated')) {
            return this.get('store').queryRecord('user', { me: true }).then((user) => {
                this.set('user', user);
            });
        } else {
            return RSVP.resolve();
        }
    }
});
1

There are 1 best solutions below

0
Software Engineer On

The simple way is to implement the restore method or you just overwrite restore() with your custom authenticator. Hope that's helpful.

you can also refer the link https://github.com/simplabs/ember-simple-auth#implementing-a-custom-authenticator

This show the options how you can make it.

I will also provide you the example:

// app/authenticators/yours.js
restore() {
  return new RSVP.Promise(res, rej){
    return resolve(data);
  }
}

This will store your session if you have already login