AngularJs module for managing authentication and authorization
Based on different literature pieces found over medium.
- download the files
- Bower
- add
"angular-security": "latest"
to yourbower.json
file then runbower install
OR runbower install angular-security
- add
- Bower
- include the files in your app
security.min.js
- include the module in angular (i.e. in
app.js
) -sh1n.angular-security
Include the AuthService dependency in your controllers in order to use its methods to shape your UI
var myController = myApp.controller('PageController', ['$scope', 'AuthService', function($scope, AuthService){
$scope.isLoggedIn = AuthService.isAuthenticated;
$scope.isAuthorized = AuthService.isAuthorized;
$scope.getUsername = AuthService.getLoginName;
}]);
<div ng-show="isLoggedIn()">
<h2>Welcome {{getUsername()}}</h2>
<a href="#" ng-show="isAuthorized('ADMIN')">Admin Panel</a>
</div>
<div ng-hide="isLoggedIn()">
<form class="LoginFormController" ng-submit="login()">
<input type="text" ng-model="credentials.identifier" placeholder="Identifier"/>
<input type="password" ng-model="credentials.password" placeholder="Password"/>
<input type="submit" />
</form>
</div>
The module fires the following set of self-explainable events on the rootScope:
- AUTH_EVENTS.loginSuccess
- AUTH_EVENTS.loginFailed
- AUTH_EVENTS.logoutSuccess
- AUTH_EVENTS.sessionTimeout
- AUTH_EVENTS.notAuthenticated
- AUTH_EVENTS.notAuthorized
The Session object stores a minimum amount of data regarding the authenticated user:
- userId
- loginName
- userRoles
The AuthService can be used in your controllers to check for authentication and authorization. It can be achieved using two methods:
- AuthService.isAuthenticated() evaluating true if the user is logged in, false otherwise.
- AuthService.isAuthorized(requiredRole) evaluating to true if the intersection between the input parameter and the user roles is not empty. It accepts both an array of strings (role names) or a single string. See the above code for usage example.
Attach it to a form and put ng-submit="login()" as its attributes in order to quickly implement a login form. It needs to populate the credentials object with both identifier and password fields. See the example above.
The code is available at github project under MIT licence.