/adapters/application.js
import DRFAdapter from './drf';
import DataAdapterMixin from 'ember-simple-auth/mixins/data-adapter-mixin';
export default DRFAdapter.extend(DataAdapterMixin, {
authorizer: 'authorizer:custom',
namespace: 'api',
pathForType(){
return '';
},
urlForCreateRecord(){
return 'http://localhost:8000/api/';
}
});
我的身份验证器文件是
/authenticators/jwt.js
import Ember from 'ember';
import Base from 'ember-simple-auth/authenticators/base';
import config from '../config/environment';
const { RSVP: { Promise }, $: { ajax }, run } = Ember;
export default Base.extend({
tokenEndpoint: `http://localhost:8000/auth`,
restore(data) {
return new Promise((resolve, reject) => {
if (!Ember.isEmpty(data.token)) {
resolve(data);
} else {
reject();
}
});
},
authenticate(creds) {
const { identification, password } = creds;
const data = JSON.stringify({
email: identification,
password: password
});
const requestOptions = {
url: this.tokenEndpoint,
type: 'POST',
data,
contentType: 'application/json',
dataType: 'json'
};
return new Promise((resolve, reject) => {
ajax(requestOptions).then((response) => {
const { jwt } = response;
// Wrapping aync operation in Ember.run
run(() => {
resolve({
token: jwt
});
});
}, (error) => {
// Wrapping aync operation in Ember.run
run(() => {
reject(error);
});
});
});
},
invalidate(data) {
return Promise.resolve(data);
}
});
登录控制器:
/login/controller.js
import Controller from '@ember/controller';
import { inject } from '@ember/service';
export default Controller.extend({
session: inject('session'),
actions: {
authenticate: function(){
let credentials = this.getProperties('identification','password');
let authenticator = 'authenticator:jwt';
this.get('session').authenticate(authenticator, credentials).catch(()=>{
this.set('errorMessage','Login Failed');
});
this.set('userData',credentials.identification);
}
}
});
/application/controller.js
import Controller from '@ember/controller';
import { inject as service } from '@ember/service';
export default Controller.extend({
session: service('session'),
actions: {
invalidateSession: function(){
this.get('session').invalidate();
}
}
});
/ p /中的Environment.js文件是
/config /environment.js
......
ENV['ember-simple-auth'] = {
authorizer: 'authorizer:custom',
// authenticationRoute: 'login',
routeAfterAuthentication: '/profiles',
//authorizationPrefix: 'JWT' - do not uncomment this line
serverTokenEndpoint: '/auth',
};
......
如您在/config/environment.js文件中所看到的,身份验证后,应用程序将重定向到路由配置文件。当我刷新配置文件路由时,会话会自动失效。我认为问题在于我还没有存储会话(我不确定,也不知道该怎么做)。