0% found this document useful (0 votes)
104 views13 pages

Aurelia Auth

The document discusses refactoring an Aurelia application to use JWT authentication. It describes modifying the AsyncHttpClient class to authenticate with a backend service, store the returned JWT in local storage, and send the token in authorization headers for subsequent requests. It also shows updating the DonationService class to rely on AsyncHttpClient for authentication instead of directly calling the backend, and checking local storage for an existing token on app startup to bypass login.

Uploaded by

nguyenvantuyen
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
104 views13 pages

Aurelia Auth

The document discusses refactoring an Aurelia application to use JWT authentication. It describes modifying the AsyncHttpClient class to authenticate with a backend service, store the returned JWT in local storage, and send the token in authorization headers for subsequent requests. It also shows updating the DonationService class to rely on AsyncHttpClient for authentication instead of directly calling the backend, and checking local storage for an existing token on app startup to bypass login.

Uploaded by

nguyenvantuyen
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Jwt in Aurelia

JWT Base Authentication


services

Simple wrapper around aurelia-


http-client

Uses async-http-client for all


API access

+ refactor these classes to


accepts a JWT on successful
authentication

+ … and transmit the token on


every subsequent api access
Refactoring AsyncHttpClient & DonationService

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

import {inject} from 'aurelia-framework';



import {HttpClient} from 'aurelia-http-client';

import Fixtures from './fixtures';

• Import import {EventAggregator} from 'aurelia-event-aggregator';

import {LoginStatus} from './messages';

LoginStatus 

@inject(HttpClient, Fixtures, EventAggregator)

export default class AsyncHttpClient {

• Inject 

constructor(httpClient, fixtures, ea) {

EventAggregator this.http = httpClient;

this.http.configure(http => {

http.withBaseUrl(fixtures.baseUrl);

});

this.ea = ea;

}

...
AsyncHttpClient authenticate()
• Post user
credentials to authenticate(url, user) {

donation-service this.http.post(url, user).then(response => {

const status = response.content;

if (status.success) {

• If success, recover this.http.configure(configuration => {

configuration.withHeader('Authorization',
JWT and store in 'bearer ' + response.content.token);

localStorage });

}

this.ea.publish(new LoginStatus(status));

• Set Authorization }).catch(error => {

const status = {

header to include success: false,

JWT for message: 'service not available'

};

subsequent api this.ea.publish(new LoginStatus(status));

calls });

}

• 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.

• Unlike cookies, this data is never transmitted to the


remote web server (unless you send it manually)

Inspect it using
developer tools
Storing Tokens in Local Storage

• donation authenticate(url, user) {


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 => {


as an const auth = JSON.parse(localStorage.donation);



http.withHeader('Authorization', 'bearer ' + auth.token);

});

‘Authorization’ }

return authenticated;

header for }

subsequent
api requests
On App Startup…

• Check to see if export class App {


token is present… ...


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

You might also like