Skip to content

Instantly share code, notes, and snippets.

@havvg
Last active March 1, 2024 11:52
Show Gist options
  • Save havvg/3925800d1657c53e8df1 to your computer and use it in GitHub Desktop.
Save havvg/3925800d1657c53e8df1 to your computer and use it in GitHub Desktop.
ExtJS 6: JSON Web Token API Login with Promises
Ext.define('App.security.Firewall', {
singleton: true,
requires: [
'App.security.TokenStorage'
],
isLoggedIn: function() {
return null !== App.security.TokenStorage.retrieve();
},
login: function(username, password) {
var deferred = new Ext.Deferred();
Ext.Ajax.request({
url: App.server.Router.generate('authenticate'),
method: 'POST',
jsonData: {
'username': username,
'password': password
},
success: function (response) {
var data = Ext.decode(response.responseText);
if (data.token) {
App.security.TokenStorage.save(data.token);
deferred.resolve(data, response);
} else {
deferred.reject(data, response);
}
},
failure: function (response) {
var data = Ext.decode(response.responseText);
App.security.TokenStorage.clear();
deferred.reject(data, response);
}
});
return deferred.promise;
},
logout: function(callback) {
App.security.TokenStorage.clear();
// The "old" way of using callbacks. You can easily rewrite this using Promise, too, see login method.
callback();
}
}, function () {
Ext.Ajax.on('beforerequest', function(conn, options) {
if (App.security.Firewall.isLoggedIn()) {
options.headers = options.headers || {};
options.headers['Authorization'] = 'Bearer ' + App.security.TokenStorage.retrieve();
}
});
});
Ext.define('App.view.login.LoginController', {
extend: 'Ext.app.ViewController',
alias: 'controller.login',
onLoginClick: function() {
var data = this.getView().down('form').getValues();
App.security.Firewall.login(data.username, data.password).then(function() {
this.getView().destroy();
Ext.create({
xtype: 'app-main'
});
}.bind(this), function(data) {
Ext.Msg.alert('Error', data.message || 'An error occurred while logging in.');
});
}
});
Ext.define('App.security.TokenStorage', {
singleton: true,
storageKey: 'json-web-token',
clear: function () {
localStorage.removeItem(this.storageKey);
},
retrieve: function() {
return localStorage.getItem(this.storageKey);
},
save: function (token) {
localStorage.setItem(this.storageKey, token);
}
});
@sseyha
Copy link

sseyha commented Aug 2, 2016

Hi,
It nice sample.
But i'm still new with "App.server.Router.generate('authenticate')"???
Could you share this code or sample please????
Thanks,
Seyha

@rattanchauhan
Copy link

rattanchauhan commented Oct 21, 2016

Hi sseyha,

I'm not sure if you still need it, but as I understand , App.server.Router.generate('authenticate') simply returns an endpoint url based on the key provided to it. So I guess the code can look like below:

Ext.define('App.server.Router', {
    singleton: true,
   hostname: 'hostname/api/',

   // method to generate URLs for endpoints
   generate: function (endpoint) {
        return this.hostname + endpoint;
    }
   // other utlity methods for routing


});

@havvg
Copy link
Author

havvg commented Oct 24, 2016

Hi @sseyha,

I'm sorry to reply so late, I didn't notice any comment on this gist. As @rattanchauhan mentioned, it's a pretty simple object:

Ext.define('App.server.Router', {
    singleton: true,
    endpoint: Ext.manifest.server.endpoint,

    routes: {
        'authenticate': '/authenticate'
        // generated list, static list .. your choice :)
    },

    generate: function(route, params) {
        // Whatever logic to determine the full URI.
        // For example, simple lookup:
        return this.endpoint + this.routes[route];
    }
});

Example using http://symfony.com/doc/current/bundles/FOSJsRoutingBundle/usage.html (with Symfony server side):

Ext.define('App.server.Router', {
    singleton: true,

    generate: function(route, params) {
        return Routing.generate(route, params);
    }
});

@albert840702
Copy link

Where is the App.security.Firewall.isLoggedIn() ??

@hlkn
Copy link

hlkn commented Jan 21, 2018

I have trouble to store and extract token using the App.security.TokenStorage with localStorage. May you help to look into using localStorage or Do I miss something from your code

@jwareservices
Copy link

Greetings havvg,
I came across this archive when searching for why my Ext JS app is not using a stored session token on Ajax requests. I'm dev'ing a front-end app using the latest SA, 4.3.3. I have a login page that uses an Ajax request to my RAD Server, which returns successfully. I then set the defaultheaders for the Session token using Ext.Ajax.defaultHeaders = {'X-Embarcadero-Session-Token' : responseData.sessionToken,}; , but on subsequent Ajax calls the token is not being sent. When viewing the dev tools in my browser I see that and I keep getting a TokenStorage.js 404 error, and I cannot figure out what is happening, which has led me to your post here.

Could I use your code to remedy this problem?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment