Implementing user authentication with JSON Web Tokens (JWT) in AngularJS involves several steps. Here's a basic outline of the process:
Install Dependencies: First, make sure you have AngularJS and any other required dependencies installed in your project.
Create Authentication Service: Create a service to handle user authentication. This service will typically have methods for login, logout, and checking authentication status.
Login Page: Create a login page where users can input their credentials.
Backend Integration: Connect your AngularJS app to a backend service (e.g., Node.js, Python Django, Java Spring Boot) that handles authentication and issues JWT tokens.
JWT Handling: Implement functions to store, retrieve, and decode JWT tokens in your AngularJS app.
Authentication Interceptor: Create an HTTP interceptor to attach the JWT token to outgoing requests and handle unauthorized responses.
Here's a basic example to get you started:
javascript// authentication.service.js
angular.module('myApp').service('AuthService', ['$http', '$window', function($http, $window) {
var self = this;
self.login = function(username, password) {
return $http.post('/api/login', { username: username, password: password })
.then(function(response) {
if (response.data.token) {
self.saveToken(response.data.token);
return true;
} else {
return false;
}
});
};
self.logout = function() {
$window.localStorage.removeItem('jwtToken');
};
self.isLoggedIn = function() {
var token = self.getToken();
if (token) {
var payload = JSON.parse($window.atob(token.split('.')[1]));
return payload.exp > Date.now() / 1000;
} else {
return false;
}
};
self.getToken = function() {
return $window.localStorage.getItem('jwtToken');
};
self.saveToken = function(token) {
$window.localStorage.setItem('jwtToken', token);
};
}]);
// authentication.interceptor.js
angular.module('myApp').factory('AuthInterceptor', ['$q', '$location', '$injector', function($q, $location, $injector) {
return {
request: function(config) {
var AuthService = $injector.get('AuthService');
var token = AuthService.getToken();
if (token) {
config.headers.Authorization = 'Bearer ' + token;
}
return config;
},
responseError: function(response) {
if (response.status === 401) {
$location.path('/login');
}
return $q.reject(response);
}
};
}]);
// app.js
angular.module('myApp', [])
.config(function($httpProvider) {
$httpProvider.interceptors.push('AuthInterceptor');
});
In this example, AuthService
handles login, logout, and token management. AuthInterceptor
intercepts HTTP requests to attach the JWT token to outgoing requests and redirects to the login page if a request is unauthorized. Make sure to replace 'myApp'
with your AngularJS module name and update the backend API endpoints accordingly.