OAuth authentication is a widely used mechanism for secure user authentication and authorization, allowing users to log in using services like Google, Facebook, GitHub, Microsoft, etc.. In AngularJS, OAuth authentication can be implemented using OAuth 2.0, which involves redirecting users to an identity provider, obtaining an access token, and using that token to access APIs securely.
1. Understanding OAuth 2.0 Workflow
OAuth 2.0 follows this authentication flow:
- User clicks “Login with Google/Facebook”
- Redirect to OAuth provider (Google, Facebook, etc.)
- User logs in & grants permission
- OAuth provider sends back an
Authorization Code
- The frontend sends the code to the backend to exchange it for an
Access Token
- Backend stores the token & sends it to the frontend
- Frontend stores the token and uses it for authenticated API calls
2. Setting Up OAuth in AngularJS
We can implement OAuth in AngularJS using OAuth 2.0 Implicit Flow (for client-side authentication) or Authorization Code Flow (recommended for security).
Choosing an OAuth Provider
You need to register your app with an OAuth provider:
- Google: Google Developer Console
- Facebook: Facebook Developers
- GitHub: GitHub OAuth Apps
After registration, you get:
Client ID
Client Secret (for backend)
Redirect URI (where users will return after authentication)
3. Installing Satellizer (OAuth Library for AngularJS)
Satellizer is a popular AngularJS OAuth library.
Install Satellizer via npm or bower:
npm install satellizer --save
or
bower install satellizer --save
Include Satellizer in Your AngularJS App:
<script src="bower_components/satellizer/satellizer.min.js"></script>
Inject Satellizer into Your AngularJS App Module:
var app = angular.module('myApp', ['satellizer']);
4. Configuring Satellizer for OAuth
Example: Configuring Google OAuth
app.config(function($authProvider) {
$authProvider.google({
clientId: 'YOUR_GOOGLE_CLIENT_ID',
redirectUri: window.location.origin
});
});
Example: Configuring Facebook OAuth
app.config(function($authProvider) {
$authProvider.facebook({
clientId: 'YOUR_FACEBOOK_CLIENT_ID',
redirectUri: window.location.origin
});
});
Other OAuth Providers Supported:
GitHub
Twitter
LinkedIn
Microsoft
5. Implementing OAuth Login in AngularJS
Now, create a login function using $auth
from Satellizer.
Login Controller Example
app.controller('AuthController', function($scope, $auth, $state) {
$scope.loginWithGoogle = function() {
$auth.authenticate('google')
.then(function(response) {
console.log('Logged in successfully:', response);
localStorage.setItem('authToken', response.data.token);
$state.go('dashboard'); // Redirect after login
})
.catch(function(error) {
console.error('Login failed:', error);
});
};
});
Login Button in HTML
<button ng-click="loginWithGoogle()">Login with Google</button>
What Happens?
✔ Clicking the button redirects to Google Login.
✔ After successful login, the access token is stored in localStorage
.
✔ The user is redirected to the dashboard.
6. Protecting Routes with Authentication
After login, we want to restrict access to certain pages.
Create an Authentication Service
app.factory('AuthService', function() {
return {
isAuthenticated: function() {
return !!localStorage.getItem('authToken');
}
};
});
Redirect Unauthorized Users
app.run(function($rootScope, $state, AuthService) {
$rootScope.$on('$stateChangeStart', function(event, toState) {
if (toState.authRequired && !AuthService.isAuthenticated()) {
event.preventDefault();
$state.go('login'); // Redirect to login if not authenticated
}
});
});
Secure Routes Example
app.config(function($stateProvider) {
$stateProvider
.state('dashboard', {
url: '/dashboard',
templateUrl: 'dashboard.html',
authRequired: true // Secure this route
})
.state('login', {
url: '/login',
templateUrl: 'login.html'
});
});
Why?
✔ Users must be logged in to access dashboard.html
.
✔ Unauthorized users are redirected to the login page.
7. Logout & Clearing Authentication Tokens
Logout Function
$scope.logout = function() {
localStorage.removeItem('authToken');
$state.go('login');
};
Logout Button in HTML
htmlCopyEdit<button ng-click="logout()">Logout</button>
What Happens?
✔ Token is removed from localStorage
.
✔ User is redirected to the login page.
8. Making Authenticated API Calls
Once logged in, send the OAuth token with API requests.
Interceptor to Attach Token to API Calls
app.factory('AuthInterceptor', function($q) {
return {
request: function(config) {
var token = localStorage.getItem('authToken');
if (token) {
config.headers.Authorization = 'Bearer ' + token;
}
return config;
}
};
});
app.config(function($httpProvider) {
$httpProvider.interceptors.push('AuthInterceptor');
});
Example API Call
$http.get('/api/user/profile')
.then(function(response) {
console.log("User Profile:", response.data);
})
.catch(function(error) {
console.error("Error fetching profile:", error);
});
Benefits:
✔ Automatically sends the token with every request.
✔ No need to manually add headers every time.
9. Handling Token Expiry & Refreshing Tokens
OAuth tokens expire after some time. To refresh the token:
- Send a refresh token request to the server
- Store the new token in
localStorage
- Replace the expired token with the new one
Interceptor for Auto-Refreshing Token
app.factory('TokenRefreshInterceptor', function($q, $http) {
return {
responseError: function(response) {
if (response.status === 401) {
return $http.post('/api/auth/refresh', { refreshToken: localStorage.getItem('refreshToken') })
.then(function(res) {
localStorage.setItem('authToken', res.data.accessToken);
response.config.headers.Authorization = 'Bearer ' + res.data.accessToken;
return $http(response.config);
});
}
return $q.reject(response);
}
};
});
app.config(function($httpProvider) {
$httpProvider.interceptors.push('TokenRefreshInterceptor');
});
Why?
✔ Automatically refreshes expired tokens.
✔ Prevents users from being logged out unexpectedly.