简体   繁体   中英

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

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();
        }
    }
});

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM