Skip to content
Rishan Solutions
Rishan Solutions
  • PowerApps
  • SharePoint online
    • Uncategorized
    • Uncategorized
  • PowerAutomate
Rishan Solutions
Latest Posts
  • Agentic AI: The Dawn of Autonomous Intelligence Revolutionizing 2025 June 24, 2025
  • Recursive Queries in T-SQL May 7, 2025
  • Generating Test Data with CROSS JOIN May 7, 2025
  • Working with Hierarchical Data May 7, 2025
  • Using TRY_CAST vs CAST May 7, 2025
  • Dynamic SQL Execution with sp_executesql May 7, 2025

Implementing OAuth authentication in AngularJS

Posted on March 27, 2025March 27, 2025 by Rishan Solutions

Loading

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:

  1. User clicks “Login with Google/Facebook”
  2. Redirect to OAuth provider (Google, Facebook, etc.)
  3. User logs in & grants permission
  4. OAuth provider sends back an Authorization Code
  5. The frontend sends the code to the backend to exchange it for an Access Token
  6. Backend stores the token & sends it to the frontend
  7. 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:

  1. Send a refresh token request to the server
  2. Store the new token in localStorage
  3. 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.

Posted Under AngularJS$httpInterceptor AngularJS AngularJS Authentication. API security Facebook Login Google Authentication JWT OAuth OAuth 2.0 route protection Satellizer Secure Login token refresh Token-Based Authentication

Post navigation

Handling authentication tokens in API calls
Consuming WebSockets for real-time updates

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Recent Posts

  • Agentic AI: The Dawn of Autonomous Intelligence Revolutionizing 2025
  • Recursive Queries in T-SQL
  • Generating Test Data with CROSS JOIN
  • Working with Hierarchical Data
  • Using TRY_CAST vs CAST

Recent Comments

  1. Michael Francis on Search , Filter and Lookup in power apps
  2. A WordPress Commenter on Hello world!

Archives

  • June 2025
  • May 2025
  • April 2025
  • March 2025
  • February 2025
  • March 2024
  • November 2023
  • October 2023
  • September 2023
  • August 2023
  • June 2023
  • May 2023
  • April 2023
  • February 2023
  • January 2023
  • December 2022
  • November 2022
  • October 2022
  • January 2022

Categories

  • Active Directory
  • AI
  • AngularJS
  • Blockchain
  • Button
  • Buttons
  • Choice Column
  • Cloud
  • Cloud Computing
  • Data Science
  • Distribution List
  • DotNet
  • Dynamics365
  • Excel Desktop
  • Extended Reality (XR) – AR, VR, MR
  • Gallery
  • Icons
  • IoT
  • Java
  • Java Script
  • jQuery
  • Microsoft Teams
  • ML
  • MS Excel
  • MS Office 365
  • MS Word
  • Office 365
  • Outlook
  • PDF File
  • PNP PowerShell
  • Power BI
  • Power Pages
  • Power Platform
  • Power Virtual Agent
  • PowerApps
  • PowerAutomate
  • PowerPoint Desktop
  • PVA
  • Python
  • Quantum Computing
  • Radio button
  • ReactJS
  • Security Groups
  • SharePoint Document library
  • SharePoint online
  • SharePoint onpremise
  • SQL
  • SQL Server
  • Template
  • Uncategorized
  • Variable
  • Visio
  • Visual Studio code
  • Windows
© Rishan Solutions 2025 | Designed by PixaHive.com.
  • Rishan Solutions