Explain Codes LogoExplain Codes Logo

Angularjs ui-router login authentication

javascript
authentication
ui-router
angularjs
Anton ShumikhinbyAnton Shumikhin·Jan 29, 2025
TLDR

To handle user authentications in AngularJS with ui-router, utilize a resolve block that calls an AuthService. Check the lucid example below:

app.config(function($stateProvider) { $stateProvider.state('secured', { url: '/secured', templateUrl: 'secured.html', resolve: { auth: function(AuthService, $state) { return AuthService.check().then(null, function() { $state.go('login'); // More like "Redirection to redemption" on fail! return Promise.reject(); }); } } }); }); app.factory('AuthService', function($q) { return { check: function() { // With great power, comes great responsibility... to check user login status! return $q.resolve(localStorage.getItem('user') ? 'authorized' : 'unauthorized'); } }; });

The check() method belongs to AuthService determines the user's login status. A rejected promise aborts the state change and $state.go('login') redirects to the login page.

Comprehensive approach to state security

Strengthen your authentication system configured with ui-router by following these handy strategies that secure the various aspects. It's about getting the most out of security and enhancing the user experience:

Checking user's authentication on application loading

Include the initialization logic within a .run() block to verify if the user is authenticated:

app.run(function(AuthService, $rootScope, $state) { $rootScope.$on('$stateChangeStart', function(event, toState) { if (!AuthService.isAuthenticated() && toState.requireAuth) { // Space invaders blocked! Prevent state change. event.preventDefault(); $state.go('login'); } }); });

Control access based on user roles

To achieve this, assign roles within your states:

$stateProvider.state('admin', { url: '/admin', templateUrl: 'admin.html', data: { roles: ['admin'] }, resolve: { // Dear users, please validate your roles first. Thank you! } });

Ensure you have an AuthorizationService for handling roles and permissions:

app.factory('AuthorizationService', function(UserService) { // Role management service... at your service! });

UI elements displayed based on authentication status or user roles

Conditionally display elements:

<div ng-show="AuthService.isAuthenticated()">Welcome home, User!</div>

Keystones of a centralized authentication service

A central AuthenticationService with methods like isAuthenticated, login, and logout can handle credentials, manage session state, and provide methods to confirm the user's current authentication state.

app.service('AuthenticationService', function($http, SessionService) { this.login = function(credentials) { // "Login you shall, store session we will," whispers Master Yoda. }; this.logout = function() { // Ready to forget? Time to bury the session in memory graveyard! }; this.isAuthenticated = function() { // Sherlock Holmes of Sessions: Finding truth in tokens, masters of mysteries! }; });

Authentication and redirection: What to focus on?

Redirection is an integral part of single-page applications (SPAs), and managing user redirection properly is vital for a secure, user-friendly application. Let's dive into key concerns:

Seamless user redirection

Ensure fluid redirects post-login using $state.go or $location.path to navigate to the intended state or return state:

app.controller('LoginController', function($scope, $state, AuthenticationService) { $scope.login = function() { AuthenticationService.login($scope.credentials).then(function() { // You are not in Kansas any more, $state.go can take you anywhere! $state.go($scope.returnState || 'dashboard'); }, function(error) { // Oh no, you got an error. You know what they say? Keep calm and login again! $scope.errorMessage = 'Login failed: ' + error.message; }); }; });

Structuring authentication-required states

Structure a state hierarchy that clearly denotes whether a state requires authentication. The data property can come in handy:

$stateProvider.state('requireAuthState', { // "Keep out! This is a private state... unless you're authenticated" - The state config data: { requireAuth: true } // other configurations... });

Securing client and server side of authentication

Combine client-side authentication checks with server-side security to bulwark against unauthorized access. A pivotal aspect to focus on would be securing your API endpoints with suitable authentication and authorization checks.

Managing roles and permissions

Easy role administration can be achieved by using libraries such as angular-permission. Below is a possible structure of your controllers for managing UI elements according to roles:

app.controller('MainController', function(PermissionStore){ PermissionStore.definePermission('isAdmin', function(stateParams) { // Calling all admins: Could this be you? }); });

Use permission checks in your views:

<div ng-if="'isAdmin' | hasPermission">Hear ye, hear ye... This is visible only to Admins.</div>