Adal Infinite redirection + Edge + Trusted sites - angularjs

Background:
I have a single page app (built using Angular) which uses adal and adal-angular to authenticate against Azure Active Directory.
Have been using version 1.0.7 of adal and adal-angular (tried using 1.0.14 as well but still no luck) and ui-router for routing.
Issue:
Few of our users are getting continuous authentication loop while trying to access the web application on Edge browser specifically.
Note that it works fine with IE, Chrome and Firefox. Surprisingly it also works fine when Edge is opened in InPrivate window.
This issue is device specific, user specific and only occurs in Edge.
Workaround:
When my site is added to the trusted sites (via Control Panel -> Internet Options), the authentication loop issue is resolved and everything works seamlessly.
Any idea why this is happening?
From what I’m assuming as of now is that it’s a cookie issue when adal writes to the auth cookie to the site and Edge can’t seem to read it?
Also any suggestions for a better fix/workaround for this? As I can’t tell all my users to go and add my website to their trusted sites collection.
Code snippet of app.js:
function authenticationInit(adalAuthenticationServiceProvider, $httpProvider, $locationProvider) {
$locationProvider.html5Mode(false);
var endpoints = {
// Map the location of a request to an API to a the identifier of the associated resource
"EndPointKey": window.config.aadEndPointUrl,
"EndPointValue": window.config.aadResouceIdUrl
};
adalAuthenticationServiceProvider.init(
{
instance: window.config.AADAuthenticationInstance,
tenant: window.config.tenant,
clientId: window.config.clientId,
extraQueryParameter: 'nux=1',
endpoints: endpoints
}, $httpProvider);
}
function registerRoutes($stateProvider) {
$stateProvider
.state('home', {
templateUrl: getViewUrl('widgets'),
controller: 'WidgetsController',
controllerAs: 'widget',
url: '/dashboard'
})
.state('terms',
{
templateUrl: getViewUrl('terms'),
controller: 'TermsController',
controllerAs: 'terms',
url: '/terms'
})
}
$rootScope.$on('$locationChangeStart', function (e) {
if (adalAuthenticationService.userInfo.isAuthenticated == false) { // Will be executed during first time login and token expiration
adalAuthenticationService.login();
}
});
$rootScope.$on("adal:loginSuccess", function (e) { // Will be executed after AAD authentication is successful
NavigationFactory.navigateTo('home');
});
Have raised the same query here- https://github.com/AzureAD/azure-activedirectory-library-for-js/issues/537

adal uses localStorage to save the tokens and reads data from it later on (you also have the option to change it to session storage). The point is that if adal is not able to write into local storage, you will not get the tokens. There is a setting in Microsoft Edge that lets the websites store data. To enable this, go to: Settings>Advanced Settings and enable: 'Let sites save protected media license on my device'. I hope this fixes your issue.

Related

Prevent session sharing between browser tabs

I have a nasty bug: open two tabs with login pages and log in with different users in each one. All requests from first tab that logged in return with 'unauthorized' error.
Frontend uses SESSION cookie and it looks like that cookie is overwritten by second successful login of the second tab and it tries to use this new cookie when browsing in the first tab.
Using Spring Boot 1.5.8, Spring-session 2, AngularJS 1.7.2
Configuration is very standard, so I don't think these boilerplates would be useful.
Until now I tried to set up a filter on backend that works before authentication, to somehow filter out requests that have known cookie, but I failed at this.
UPD:
Some way of preventing that situation when a user is logged in but with incorrect session is what I seek. Either blocking second login attempt in this browser, or kicking already logged in user when another one logs in in the same broser - all will do.
You can log out user from other tabs if you set some sort of token on local storage like the code below(in sucessfull login response from server )
localStorage.setItem('logout', 'logout-' + Math.random());
and have this function as a run block in your main app module:
function logoutFromOtherTabs(authService, $timeout) {
'ngInject';
window.addEventListener('storage', function (event) {
if (event.key === 'logout') {
$timeout(function () {
authService.logout();
}, 1000);
}
});

Angular ADAL requires authentication for non authenticated routes

Scenario is AngularJS 1.6.5 SPA, c# WebAPI and Azure AD (AAD) for authentication. I'm using Angular-ADAL library to handle the authentication and angular-route to handle routes. Strange thing is that routes that CAN be anonymous (i.e. DO NOT require the requireADLogin: true in the route definition) but need to go to the backend (for example to get an image or to get data from the API), get intercepted by ADAL and never get to the backend/API.
My routes are defined like so, when I want a route protected:
.when('/clasesDeDocumento', {
templateUrl: 'app/views/mantenedores/clasesDeDocumento/clasesDeDocumento.html',
controller: 'clasesDeDocumentoController',
controllerAs: 'vm',
requireADLogin: true,
title: "clases de documentos"
})
And similar to the above, but without the requiredADLogin: true when not protected.
According to the documentation:
Routes that do not specify the requireADLogin=true property are added to the anonymousEndpoints array automatically.
Clicking on an unprotected link does not take you to the Azaure Authentication page, however the backend/API request gets intercepted and an error is thrown.
I have solved this (manually) adding an anonymousEndpoints array, but for larger applications, this would not be feasible.
Any ideas?
This is expected behavior. The requireADLogin and anonymousEndpoints parameters are used for the different purpose.
The requireADLogin is used for the whether the routes are needle to protect. If it is true, the app will requires users to authenticate first before they can access the route.
The anonymousEndpoints parameter is used help the adal library to determine whether the $http service required to inject the token. And by default, the route URL will be added into the anonymousEndpoints if we doesn't specify the requireADLogin parameter to true(refer the routeChangeHandler).

ADAL.JS with Mobile App

I'm trying to integrate some Oracle delivered Mobile Application Framework Apps (MAF) mobile apps with Azure AD authentication. I have tried the Java approach, which apparently doesn't work in my case.
So I decided to try using a Javascript login page option using ADAL.JS. Since MAF creates cross-platform compatible code by transpiling to HTML 5/Javascript/Cordova, I reckoned I could make the JS option work without resorting to having multiple SDK specific solutions like ADAL-Android or ADAL-IOS. Since I can wrap it all in an HTML page as I can use the OAUTH implicit flow option that ADAL.JS requires. I have the ADAL.JS part working from my PC using this example with a local Node/Webpack dev server for the redirect URI. (Note, just like that example, I'd prefer to use the strict adal.js option and avoid any angular-js stuff). However, I'm running into an issue when deployed on the Android mobile device. It appears to be due to the reply URI. After being prompted for Azure credentials and supplying those, the following error is produced.
AADSTS50011: Reply address 'file:///data/user/0/com.company.app/storage/assets/FARs/ViewController/public_html/SignOn/login.html' has an invalid scheme.
I found that when deploying to a mobile device the Azure registered app must be set to type "Native" instead of "Web/API" which I have done. And according to an MSFT example (which I cannot include since I don't have enough rep to include more than two links) the redirect URI must be set to "https://login.microsoftonline.com/common/oauth2/nativeclient". But I still get the same error.
UPDATE since #FeiXue Reply
I'm using the original endpoint not 2.0. When I set the redirectURI as such:
redirectURI=https://login.microsoftonline.com/common/oauth2/nativeclient
The browser returns this in the address bar and remains there on a blank screen and does not issue a token. It does this both on the PC browser and mobile browser.
http://login.microsoftonline.com/common/oauth2/nativeclient#id_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6ImEzUU4wQlpTN3M0bk4tQmRyamJGMFlfTGRNTSIsImtpZCI6ImEzUU4wQlpTN3M0bk4tQmRyamJGMFlfTGRNTSJ9.(shortened for brevity)&state=e1ce94fb-6310-4dec-9e8b-053727ceb9b8&session_state=1beafa4d-af55-415b-85d5-83e8b4035594
However, for the exact same code, on the PC when I set the redirectURI as such it returns an access token:
redirectURI=https://localhost:8443 <-- port to my local node server
I've also tried it with a redirectURI of urn:ietf:wg:oauth:2.0:oob, but that does not work either.
Code
<!DOCTYPE html>
<html>
<head>
<title>Authenticate User with ADAL JS</title>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://secure.aadcdn.microsoftonline-p.com/lib/1.0.0/js/adal.js"></script>
<script type="text/javascript">
$(document).ready(function() {
"use strict";
var variables = {
azureAD: "mytenant.onmicrosoft.com",
clientId: "cc8ed7e0-56e9-45c9-b01e-xxxxxxxxxx"
}
window.config = {
tenant: variables.azureAD,
clientId: variables.clientId,
postLogoutRedirectUri: window.location.origin,
redirectUri: "https://login.microsoftonline.com/common/oauth2/nativeclient",
endpoints: {
aisApiUri: "cc8ed7e0-56e9-45c9-b01e-xxxxxxxxxx"
}
//cacheLocation: "localStorage"
};
var authContext = new AuthenticationContext(config);
var isCallback = authContext.isCallback(window.location.hash);
authContext.handleWindowCallback();
if (isCallback && !authContext.getLoginError()) {
window.location = authContext._getItem(authContext.CONSTANTS.STORAGE.LOGIN_REQUEST);
}
var user = authContext.getCachedUser();
if (!user) {
authContext.login();
}
authContext.acquireToken(config.endpoints.aisApiUri, function (error, token) {
if (error || !token) {
console.log("ADAL error occurred in acquireToken: " + error);
return;
}
else {
var accessToken = "Authorization:" + " Bearer " + token;
console.log("SUCCESSFULLY FETCHED TOKEN: " + accessToken);
}
});
});
</script>
</head>
<body>
<h1>Test Login</h1>
</body>
</html>
Update
#FeiXue So I guess from what you're saying the id_token IS the access token? I think then the problem is this.
When the redirectURI="https://localhost:8443" it redirects back to my index.html after AAD login and the authContext.acquireToken() works and returns a valid token.
But when the redirectURI="https://login.microsoftonline.com/common/oauth2/nativeclient" it never redirects back from http://login.microsoftonline.com/common/oauth2/nativeclient#id_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1Ni......
While it shows the id_token, it never redirects back to my index.html So I can't make a call to authContext.acquireToken() for passing it onto my web API.
From my research on this topic here is the gist on ADAL.JS and Native (Mobile) Device Support
As #fei-xue-msft mentioned, ADAL.JS is not intended for nor does it work with native/mobile devices. ADAL.JS was written with the “original” Azure endpoint in mind, not the v2.0 endpoint that provides more functionality for mobile/native devices (see more below on the two different endpoint options). There is however an experimental ADAL.JS branch you can try (uses the v2.0 endpoint), but it is not not being actively updated anymore so you are on your own. The new MSFT approach is to use the new MSAL library, which is written towards the v2.0 endpoints. However there is no MSAL-for-JS library yet but rumor is there will be one at some point. For more on the two different Azure endpoints (“original” versus “v2.0”) see the links below. The confusion over this was a source of frustration in my troubleshooting so I help this helps some others going down this track.
So if you are looking to get Azure Oauth authentication on mobile devices, first decide which Azure Endpoint you want to use (Supporting links on that below as v2.0 does have some restrictions that the original endpoint does not). You can determine what your specific endpoints for your tenant are by viewing the Metadata Doc links listed below, just substitute your tenant name or ID. You should be able to use either.
To register an application for a specific type of endpoint (original versus v2.0) use the appropriate App Registration Portal link cited below. Then, to decide what your options are for creating an Azure auth solution for native/mobile device, see the code samples for each endpoint version, and make sure the sample is for “native” else it probably won’t work on your mobile device. For example, you will not see an ADAL.JS sample for the original endpoint library options, but you will see one for Cordova (which is why #fei-xue-msft suggested that approach). For the v2.0 endpoint samples you will see the MSAL/Xamarin options, and for an Javascript option you can try something like the Hello.JS Sample.
Original Endpoint
https://login.microsoft.com/{tenant id}/oauth2/authorize
App Registration Portal: https://portal.azure.com
Code Samples: https://learn.microsoft.com/en-us/azure/active-directory/develop/active-directory-code-samples#native-application-to-web-api
Native Auth Scenarios: https://learn.microsoft.com/en-us/azure/active-directory/develop/active-directory-authentication-scenarios#native-application-to-web-api
OpenID Metadata Doc: https://login.microsoft.com/{tenant id}/.well-known/openid-configuration
V2.0 Endpoint
https://login.microsoftonline.com/{tenant id}/oauth2/v2.0/authorize
App Registration Portal: https://apps.dev.microsoft.com
V2.0 Endpoint Compare: https://learn.microsoft.com/en-us/azure/active-directory/develop/active-directory-v2-compare
Code Sample: https://learn.microsoft.com/en-us/azure/active-directory/develop/active-directory-v2-libraries
OpenID Metadata Doc: https://login.microsoft.com/{tenant id}/v2.0/.well-known/openid-configuration
Are you developing with Azure AD V2.0 endpoint?
If not, we are able to config the redirect URIs as we want on the portal for the native app. However as the error message indicates that the file protocol is not a a validate scheme.
In this scenario, we can use the http or https since you were developing with HTML.
And in the Azure AD V2.0 endpoint, we are not able to set the redirect_Uri for the native app at present. We can use urn:ietf:wg:oauth:2.0:oob or https://login.microsoftonline.com/common/oauth2/nativeclient for the redirect_Uri. The first one is used for the native app for the device and the second we can use for the client which host in browser(web-view).
At last, please ensure that the redirect_uri in the request is using the correct one you register for the portal. You can also test the request on the browser to narrow down whether this issue was cause the incorrect redirect_uri in the request. And for the authorization request, you can refer links below:
Authorize access to web applications using OAuth 2.0 and Azure Active Directory
v2.0 Protocols - OAuth 2.0 Authorization Code Flow
Update(there is no href property if open the HTML from disk which cause the popup page is not closed)
AuthenticationContext.prototype._loginPopup = function (urlNavigate) {
var popupWindow = this._openPopup(urlNavigate, "login", this.CONSTANTS.POPUP_WIDTH, this.CONSTANTS.POPUP_HEIGHT);
if (popupWindow == null) {
this.warn('Popup Window is null. This can happen if you are using IE');
this._saveItem(this.CONSTANTS.STORAGE.ERROR, 'Error opening popup');
this._saveItem(this.CONSTANTS.STORAGE.ERROR_DESCRIPTION, 'Popup Window is null. This can happen if you are using IE');
this._saveItem(this.CONSTANTS.STORAGE.LOGIN_ERROR, 'Popup Window is null. This can happen if you are using IE');
if (this.callback)
this.callback(this._getItem(this.CONSTANTS.STORAGE.LOGIN_ERROR), null, this._getItem(this.CONSTANTS.STORAGE.ERROR));
return;
}
if (this.config.redirectUri.indexOf('#') != -1)
var registeredRedirectUri = this.config.redirectUri.split("#")[0];
else
var registeredRedirectUri = this.config.redirectUri;
var that = this;
var pollTimer = window.setInterval(function () {
if (!popupWindow || popupWindow.closed || popupWindow.closed === undefined) {
that._loginInProgress = false;
window.clearInterval(pollTimer);
}
try {
//there is no href property if open the HTML from disk
if (popupWindow.location.href.indexOf(registeredRedirectUri) != -1) {
if (that.isAngular) {
that._onPopUpHashChanged(popupWindow.location.hash);
}
else {
that.handleWindowCallback(popupWindow.location.hash);
}
window.clearInterval(pollTimer);
that._loginInProgress = false;
that.info("Closing popup window");
popupWindow.close();
}
} catch (e) {
}
}, 20);
};
This issue is caused that when we open the HTML page from device(disk), the parent HTML page(login page) is not able to get the location of the popup page. So the parent page is not able to close that page based on the location of popup page. To workaround this issue, I suggest that you developing with azure-activedirectory-library-for-cordova or host the login page on the back end of web API.

Firebase $onAuth has wrong authData after $authWithOAuthRedirect from Facebook

I am trying to authenticate users of my Firebase (Angularfire) app with Facebook Login.
Everything works as expected when I authenticate with a pop-up window, but to support as many browsers as possible (Chrome on iOS doesn't support pop-ups, for e.g.) I want to fallback to authenticating with a redirect ($authWithOAuthRedirect).
I have confirmed my setting in Facebook are correct (my app ID and secret, for e.g.) but when I am redirected back to my app after Facebook authenticating with a redirect, $onAuth fires but I don't have my Facebook authData.
Instead, I have anonymous authData. For a bit of background; all users are authenticated anonymously if they are not otherwise authenticated (with Facebook, in this e.g.).
I can't see to find why this would be - the user should now be authenticated with Facebook, and have the Facebook authData.
Excepts of my code are below for some context:
Triggered when a user clicks the login button
function logIn () {
firebaseAuth
.$authWithOAuthRedirect('facebook', function (error) {
if (error) {
console.log(error);
}
});
}
$onAuth (inside my Angular app's run)
function run ($rootScope, firebaseAuth, sessionStore) {
$rootScope
.$on('$routeChangeError', function (event, next, prev, error) {
if (error === 'AUTH_REQUIRED') {
console.log(error);
}
});
$rootScope
.$on('$routeChangeSuccess', function (event, current, prev) {
$rootScope.title = current.$$route.title;
});
firebaseAuth
.$onAuth(onAuth);
function onAuth (authData) {
console.log(authData);
}
}
Route resolver to otherwise anonymously authenticates users
function sessionState ($q, firebaseAuth) {
var deferred = $q.defer();
firebaseAuth
.$requireAuth()
.then(deferred.resolve, guest);
return deferred.promise;
function guest () {
firebaseAuth
.$authAnonymously()
.then(deferred.resolve, rejected);
}
function rejected () {
deferred.reject('AUTH_REQUIRED');
}
}
The route resolver (sessionState) checks to see if the user is authenticated already, and if not, tries to anonymously authenticate them.
After the Facebook authentication redirect, the user will already be authenticated, and therefore does not need to be anonymously authenticated.
But, it appears that they are? As $onAuth logs the authData to the console, and it is anonymous.
Any help with this would be much appreciated! I am sure it has something to do with my route resolver, as pop-up authentication works fine (the route is already resolved).
EDIT: I tried completely removing my route resolver in case it was that causing an issue, but it made no difference. The user was just 'unauthenticated' instead of being either authenticated with Facebook (after $authWithOAuthRedirect) or anonymously.
UPDATE: I tried authenticating with Twitter and the redirect transport and I have encountered the exact same problem. I have also tried using port 80, instead of port 3000 that my app was being served on locally, but no joy.
UPDATE: When I turn off html5Mode mode in my app - and routes now begin with #s - $authWithOAuthRedirect works perfectly. From this I can only assume that $authWithOAuthRedirect does not support AngularJS's html5Mode. Can anyone confirm this is an issue, or do I need to change my code to support html5Mode and authWithOAuthRedirect?
EXAMPLE REPO Here is an example repo demonstrating the problem: https://github.com/jonathonoates/myapp
Look in the dist directory - you should be able to download this and run the app to reproduce the problem. In scripts/main.js is the app's JS; I've added a couple of comments but it's pretty self explanatory.
To reproduce the problem: click on the 'Facebook Login' button, and you'll be redirected to Facebook to authenticate. FB will redirect you back to the app, but here lies the problem - you won't be authenticated, and the returned authData will be null - you'll see this in the console
UPDATE: When I add a hashPrefix in html5Mode e.g.
$locationProvider
.html5Mode(true)
.hashPrefix('!');
The app works as I would expect - authenticating with Facebook and the redirect transport works.
Couple of niggles though:
The URL has #%3F appended to it, and is available/visible in the browser's history.
This would rewrite URLs with #! in browsers that do not support History.pushState (html5Mode), and some less advanced search engines might look for a HTML fragment because of the 'hashbang'.
I'll look into highjacking the URL upon being redirected back from Facebook instead of using hashPrefix. In the URL there is a __firebase_request_key which may be significant e.g.
http://localhost:3000/#%3F&__firebase_request_key=
It looks like this is indeed an incompatibility between Firebase and AngularJS's html5mode as you suspected. At the end of the redirect flow, Firebase was leaving the URL as "http://.../#?", and Angular apparently doesn't like that so it did a redirect to "http://.../" This redirect interrupts Firebase (the page reloads while we're trying to auth against the backend) and so it is unable to complete the authentication process.
I've made an experimental fix that ensures we revert the URL to http://.../#" at the end of the redirect flow, which Angular is happy with, thus preventing the problematic redirect. You can grab it here if you like: https://mike-shared.firebaseapp.com/firebase.js
I'll make sure this fix gets into the next version of the JS client. You can keep an eye on our changelog to see when it is released.

UI Router and Satellizer force login

I know this question isn't very specific, but I have no idea how to solve this issue or where I should begin..
I'm using Satellizer for authentication with UI-Router. the problem is I have 2 routes /sign_in and /profile the /sign_in issue a request to the server returning the user info (when successful login)... this currentUser info is used all over the application...
the problem is when a user try to go to /profile before login, it renders the empty view... how do I enforce user to login first before accessing these "restricted" views ?!
again I know this isn't a specific question but I really don't know where to start
Have a look into handling the routechangestart event on UI router, I did something similar.
I think this will give you some clues http://arthur.gonigberg.com/2013/06/29/angularjs-role-based-auth/
The key is that you need to create some form of authentication service where you can store the logged in state of the user, and since a service is invoked once (singleton) it is shared across your app (controllers, other services, etc). Then in the routechangestart event handling you can prevent routing to the target page and redirect to login if user is not authenticated.
I found the answer in this Github Repo
the idea is to have role based authentication as discussed in the Repo readme.
so the code for forbidding the unauthorised access to /profile would be something like the following
$stateProvider.state("profile", {
url: "/profile",
templateUrl: "app/profile/profile.html",
controller: "ProfileCtrl",
controllerAs: "user",
data: {
permissions: {
except: ['guest'],
redirectTo: 'sign_in'
}
}
});
given that you defined the guest role
definePermissions = function(Permission, Identity) {
Permission.defineRole('guest', function(stateParams) {
return !Identity.currentUser;
});
};

Resources