In this article I’m going to describe the way I use LoopBack’s authentication service in connection with an AngularJS app on client side. While primarily based on the LoopBack getting started intermediate tutorial, I tried to merge in John Papa’s style guidelines as well as a few other blog posts on the matter.
LoopBack offers a flexible system to build an authentication system that suits the demands of your application. The documentation on Users, Roles, RoleMappings, ACLs etc. is quite comprehensive , so I don’t feel like there is a lot to add on this side. AngularJS will use the automatically generated services in lbServices.js to communicate via the REST API.
Of course, everything we are going to do here is providing a nice user experience by hiding routes and endpoints the current user has no access on. Since all code can possibly be altered by the client, essential security measures are to be taken on server side.
As LoopBack already offers a solid groundwork, the only real addition is a broadcasting system offering authentication status changes so that all parts of the application can adapt to new situations accordingly. I picked up a lot of ideas from a wonderful article by Gert Hengeveld in which he introduces a broadcasting system based on constants for the respective authentication states. Angular’s broadcast system is a controversy topic and according to the widely recognized Angular Style Guide by John Papa , we should avoid using it at all. However, while I see the risks of event-spamming if we talk about inter-controller communication, an authentication state broadcasting system is probably the only case where I opt for Angular events.
The basic idea is that whenever a call to
authService is made, we make sure to publish all relevant state changes using Angular broadcasts. These are, among others you might find useful in your application,
The following diagram is showing dependencies between the components in the discussed authentication-state broadcasting system. The dashed lines are injects.
Next, I tried to model a basic procedure where a user submits the login form and gets redirected to the application’s main page. Since the user is authenticated after that, the menu bar has to show differing items and maybe include the user name in the upper right corner. The diagram below shows all that.