Aurelia Auth
Aurelia Auth
AsyncHttpClient DonationService
• Introduce new • Simplify approach
‘authenticate()’ method into
AsyncHttpClient • No longer retrieve list of
users
• Retrieve JWT from server (if
correct credentials sent) • just invoke ‘authenticate()’
AsyncHttpClient
• Store the token, and send
with each subsequent api • Rely on AsyncHttpClient
request
to generate ‘loggedIn/
loggedOut’ events
• Clear the Token on logout
AsyncHttpClient Constructor
• Publish
LoginStatus event
AsyncHttpClient clearAuthentication()
• Clear the
Authorization
header clearAuthentication() {
this.http.configure(configuration => {
configuration.withHeader('Authorization', '');
});
}
DonationService - Constructor
donation-web
donation-client exports.find = {
export default class DonationService {
auth: false,
donations = [];
handler: function (request, reply) {
methods = [];
Candidate.find({}).exec().then(candidates => {
candidates = [];
reply(candidates);
users = [];
}).catch(err => {
total = 0;
reply(Boom.badImplementation('error accessing db'));
});
constructor(data, ea, ac) {
},
this.methods = data.methods;
}
this.ea = ea;
this.ac = ac;
exports.find = {
this.getCandidates();
// this.getUsers();
auth: {
} strategy: 'jwt',
},
handler: function (request, reply) {
User.find({}).exec().then(users => {
• candidates ‘open’ route reply(users);
}).catch(err => {
reply(Boom.badImplementation('error accessing db'));
• getUser ‘closed’ route },
});
};
DonationService - login/logout
login(email, password) {
• Login defers to const user = {
email: email,
asyncHttpClient };
password: password
this.ac.authenticate('/api/users/authenticate', user);
}
• Logout asks asks
logout() {
asyncHttpClient const status = {
success: false,
to clear the JWT, message: ''
};
and then this.ac.clearAuthentication();
this.ea.publish(new LoginStatus(new LoginStatus(status)));
broadcasts new }
status
• A html5 standard way for web pages to store
named key/value pairs locally, within the client web
Local
browser. Storage
• Like cookies, this data persists even after you
navigate away from the web site, close your
browser tab, exit your browser.
Inspect it using
developer tools
Storing Tokens in Local Storage
name
this.http.post(url, user).then(response => {
const status = response.content;
if (status.success) {
value pair localStorage.donation = JSON.stringify(response.content);
this.http.configure(configuration => {
created configuration.withHeader('Authorization',
'bearer ' + response.content.token);
in local }
});
storage ...
}
Check LocalStorage for Tokens
• If token is
found: isAuthenticated() {
let authenticated = false;
if (localStorage.donation !== 'null') {
• set the token authenticated = true;
this.http.configure(http => {
subsequent
api requests
On App Startup…
attached() {
if (this.ds.isAuthenticated()) {
• … if it is, bypass this.au.setRoot('home').then(() => {
this.router.navigateToRoute('dashboard');
login/signup routes });
}
and go straight to }
}
‘home’ router