Azure AD Easy Auth expires even when users are actively using application - azure-web-app-service

We have a Single Page App (SPA) that uses Azure Active Directory "Easy Auth", e.g., the code-less solution. This seems to work ok when users first open the the application. They are redirected to the Microsoft login page and they can authenticate and then access the application.
Then, because its an SPA, users will navigate around and only fire Ajax requests. The problems come approximately 24 hours later when the session cookie expires. Users likely still have the same browser tab open and do not perform a full page refresh. Then they may be working on a record and at some point their next Ajax PUT request fails with a Redirect HTTP status and they loose their work.
So they key question is:
How can we make SPA Ajax requests extend a current user's session so that their session will not expire when they are actively using the application?
It seems like the Azure AD Easy Auth service does not "honor" activity on the part of the user, which leads us to believe that the session cookie never gets updated.
Note: We've recently done some testing with the /.auth/refresh endpoint and this does not solve the problem either.

There are several ways you can possibly solve this. Here are a few that I can think of:
Use local storage: The problem you mentioned is that user's lose their work due to the redirects. The problem of losing work can be solved if you persist the in-progress state in local storage so that it's available when they are redirected back to the page.
Switch to using tokens: The /.auth/refresh endpoint doesn't refresh the AppServiceAuthSession when using AAD because AAD doesn't support refreshing the user information. What you can do instead is authenticate with your backend using the x-zumo-auth tokens. The /.auth/refresh endpoint will correctly refresh these tokens. If you're explicitly logging in users using /.auth/login/aad, then you can add the session_mode=token as a query string parameter. This is done for you if you use the Mobile Apps JavaScript SDK. If login is automatic, then you'll need to add session_mode=token in the additionalLoginParams setting of your auth config. You can then parse the authentication token from the #token fragment which is added to the URL after the login completes.
Use hidden iframes: I haven't tried this myself, but if you can get it working it might require the least amount of code change. The idea is that you use a hidden iframe to re-login the user periodically when you detect they are active. The iframe would need to point to something like ./auth/login/aad?prompt=none&domain_hint={userdomain.com} where {userdomain.com} is the last part of the user's email address - e.g. contoso.com. These parameters get passed to the AAD login page, and the login should complete automatically without any user interaction. Test it manually a few times in a browser window to make sure it works correctly. The result should be an updated auth cookie with a fresh expiration.
Let me know in the comments if you have any questions or issues with any of these options.

Expanding on Chris Gillum's answer with implementation example:
Scenario: Single Page Application (SPA) with Progressive Web App (PWA) capabilities, hosted in Azure Web App. Added authentication using Azure Web Authentication/EasyAuth.
Ran into similar/same issue: Initial loads of the SPA worked fine, but after period of hour(s) (token expires) the app "breaks" - in SPA on iOS tablet that manifested for me with endless whitescreen and seemingly no practical fix (force killing did NOT resolve). Error messages thrown ranged from 401 (understandable) to service-worker refusing to process scripts/handle 302 redirects/etc (less obvious where problem may be).
SPA + Azure Web Authentication/EasyAuth tweaks:
If using MDM, disable "Block Safari navigation menu bar" feature in the MDM for this app. This appears to allow the app to work as expected after force kill (it would reload the page, see expired token, redirect to login and then back to the app). I'm not sure if this behavior is controllable in manifest.json, may be iOS specific capability.
Hidden iframe refreshing of token + Timer/check token periodically (in ajax calls, etc):
Note: As of ~2021-04, Chromium based browser worked with hidden iframe method. For other browsers the AAD page would experience errors and fail - current solution suggested would be storing app state -> navigate to AAD login page with redirect param -> User logs in and redirected back to the app -> App state restored w/ refreshed token.
refreshAuthToken() {
//Chrome based browsers work with silent iFrame based token reAuth
if (this.browserChromium()) {
let domainHint = "contoso.com"; //Domain of your organization users (e.g. me#contoso.com)
//Remove existing iframe (if exists), to minimize history/back button entries
let existingFrame = document.getElementById("authIFrame");
if (existingFrame) {
existingFrame.remove();
}
//Inject iFrame that will call endpoint to refresh token/cookie
console.log("Refreshing auth token (quietly)...");
let iframe = document.createElement("iframe");
iframe.id = "authIFrame";
iframe.style =
"width: 0; height: 0; border: 0; border: none; position: absolute; visibility: hidden;";
iframe.src = `/.auth/login/aad?prompt=none&domain_hint=${domainHint}`;
document.body.appendChild(iframe);
new Promise(r => setTimeout(r, 2000)).finally(() => resolve()); //Hacky method of "waiting" for iframe to finish
} else {
console.log("Refreshing auth token (via page reload)...");
window.location.replace("/.auth/login/aad?post_login_redirect_url=/?restoreData=true");
}
},
//
// Timer example:
//
setInterval(() => {this.refreshAuthToken()}, 1000 * 60 * 5); //Fire every 5 minutes
//
// And/or periodically call this function maintain token freshness
//
checkAuthToken() {
//this.authEnd = JWT from /.auth/me "exp" claim
let now = new Date() / 1000;
let expirationWindow = this.authEnd - 600; // Consider token expiring if 10 minutes or less remaining
if (now >= expirationWindow) {
console.log("Auth Token expired - Refreshing...")
this.refreshAuthToken();
} else {
// console.log("Auth token still healthy.");
}
}
Nicety: Enable anonymous access to PWA icons (if possible). iOS requires icons be publicly accessible when saving PWA to homescreen, otherwise uses screenshot of app rather than formal icon: https://stackoverflow.com/a/67116374/7650275

Related

Prevent showing the UI5 app internal page without successful authentication

OpenUI5 version: 1.86
Browser/version (+device/version): Chrome Dev
Upon the authentication I validate the user session:
if (isUserSessionValid) {
const oRouter = UIComponent.getRouterFor(this);
oRouter.navTo("overview");
} else {
this.getOwnerComponent().openAuthDialog();
}
If isUserSessionValid is true, then I forward an user to the internal page, otherwise I show the login dialog.
The problem is, however, that an user can change the value of isUserSessionValid in DevTools and then getting forwarded to the UI5 app internal page. Of course, due to a lack of a valid session, no piece of the business data will be displayed, just an empty UI5 app template, but I would like to prevent even such screen.
If it would be a classical webapp, I would just send an appropriate server response with a redirect to the login page (e.g. res.redirect(403, "/login");). But, if I understand it correctly, since I'm sending am asynchronous request, a plain res.redirect won't work out and I'm required to implement a redirection logic on the UI5-client, which can be manipulated and bypassed by user.
How to prevent a manipulation of a view navigation in UI5 and ensure that unauthorized user can't get any piece of the UI5-app code?
The answer from SAP:
If you want to prevent an unauthorized user from accessing the client-side code (e.g. view/controller) you need to enforce
authorization on the server also for those static files. When bundling
the application code you also need to ensure that those files are
separate from the "public" files. One approach would be to have 2
separate components, one for the public page/auth dialog and one for
the actual application.

How to fill login prompt with Webdriver IO?

I'm working on a CLI with OCLIF. In one of the commands, I need to simulate a couple of clicks on a web page (using the WebdriverIO framework for that). Before you're able to reach the desired page, there is a redirect to a page with a login prompt. When I use WebdriverIO methods related to alerts such as browser.getAlertText(), browser.sendAlertText() or browser.acceptAlert, I always get the error no such alert.
As an alternative, I tried to get the URL when I am on the page that shows the login prompt. With the URL, I wanted to do something like browser.url(https://<username>:<password>#<url>) to circumvent the prompt. However, browser.url() returns chrome-error://chromewebdata/ as URL when I'm on that page. I guess because the focus is on the prompt and that doesn't have an URL. I also don't know the URL before I land on that page. When being redirected, a query string parameter containing a token is added to the URL that I need.
A screenshot of the prompt:
Is it possible to handle this scenario with WebdriverIO? And if so, how?
You are on the right track, probably there are some fine-tunings that you need to address to get it working.
First off, regarding the chrome-error://chromewebdata errors, quoting Chrome DOCs:
If you see errors with a location like chrome-error://chromewebdata/
in the error stack, these errors are not from the extension or from
your app - they are usually a sign that Chrome was not able to load
your app.
When you see these errors, first check whether Chrome was able to load
your app. Does Chrome say "This site can't be reached" or something
similar? You must start your own server to run your app. Double-check
that your server is running, and that the url and port are configured
correctly.
A lot of words that sum up to: Chrome couldn't load the URL you used inside the browser.url() command.
I tried myself on The Internet - Basic Auth page. It worked like a charm.
URL without basic auth credentials:
URL WITH basic auth credentials:
Code used:
it('Bypass HTTP basic auth', () => {
browser.url('https://admin:admin#the-internet.herokuapp.com/basic_auth');
browser.waitForReadyState('complete');
const banner = $('div.example p').getText().trim();
expect(banner).to.equal('Congratulations! You must have the proper credentials.');
});
What I'd do is manually go through each step, trying to emulate the same flow in the script you're using. From history I can tell you, I dealt with some HTTP web-apps that required a refresh after issuing the basic auth browser.url() call.
Another way to tackle this is to make use of some custom browser profiles (Firefox | Chrome) . I know I wrote a tutorial on it somewhere on SO, but I'm too lazy to find it. I reference a similar post here.
Short story, manually complete the basic auth flow (logging in with credentials) in an incognito window (as to isolate the configurations). Open chrome://version/ in another tab of that session and store the contents of the Profile Path. That folder in going to keep all your sessions & preserve cookies and other browser data.
Lastly, in your currentCapabilities, update the browser-specific options to start the sessions with a custom profile, via the '--user-data-dir=/path/to/your/custom/profile. It should look something like this:
'goog:chromeOptions': {
args: [
'--user-data-dir=/Users/iamdanchiv/Desktop/scoped_dir18256_17319',
],
}
Good luck!

Getting a valid Google access token for Chrome Web Store APIs access from outside a Chrome Extension

I have an issue over Google OAuth and Chrome Web Store APis.
Some context before starting with the tech stuff.
I have a popular Chrome Extension that delivers in-app purchases: purchasing an item the extension goes "pro", so usage limits are expanded.
Last year the audience asked me to make a porting on Firefox (thanks to the newly available WebExtentions APIs), and I started delivering both versions.
The Firefox version does not support in-app purchase at this moment, but people are starting to ask for it (let's think the FF version as an alpha version, so not all features are guarantee to be supported).
Problem: That said, I don't want to implement a secondary payment service using Google Pay APIs or other similar APIs and I'd like that if a user makes an in-app purchase on Chrome, it is delivered on FF as well.
Hoped Solution: I thought it would have been easy to use the Google Chrome Web Store APIs. Making an user authorising its Google Account from the FF add-on I could understand if it was a paying user or not, thus enabling or disabling the "pro" limits.
Here are the steps I did.
Step 1 - Create a new app on the Google Cloud Console (I already have the one used on the Chrome Extension):
And enable the Chrome Web Store APIs:
Step 2 - Jump on Firefox JS console (inside the Options page of the add-on, so I have all the WebExtensions APIs enabled), and call the method to get a valid token (the code is quick and dirty, not enhanced and written just as a POC):
var scopes = ['https://www.googleapis.com/auth/plus.login',
'https://www.googleapis.com/auth/chromewebstore.readonly'];
var url = 'https://accounts.google.com/o/oauth2/v2/auth?'
+ 'client_id=xxxxxxxx.apps.googleusercontent.com'
+ '&response_type=token'
+ '&scope='
+encodeURIComponent(scopes.join(' '))
+ '&redirect_uri='
+encodeURIComponent(browser.identity.getRedirectURL());
browser.identity.launchWebAuthFlow(
{interactive: true, url: url})
.then(function(result){
console.log(result);
})
.catch(function(err){
console.log(err);
});
Using the browser.identity.launchWebAuthFlow() function I got a valid token from the returning result (in the query string on the access_token parameter).
Now I get call the Chrome WebStore APIs with no issue (I thought) with this simple code:
//access token
var token = 'previous_access_token';
//Google Chrome immutable Ext. ID from the store
var GOOGLE_CHROME_EXTENSION_ID = 'XXXXYYYYZZZ....';
//endpoint to get all purchased items (see https://developer.chrome.com/webstore/webstore_api/payments#resource)
var CWS_LICENSE_API_URL = 'https://www.googleapis.com/chromewebstore/v1.1/items/';
var req = new XMLHttpRequest();
req.open('GET', CWS_LICENSE_API_URL+ GOOGLE_CHROME_EXTENSION_ID + '/payments');
req.setRequestHeader('Authorization', 'Bearer ' + token);
req.onreadystatechange = function() {
if (req.readyState == 4) {
var license = JSON.parse(req.responseText);
console.log(license);
}
}
req.send();
Unfortunately this doesn't work at all, getting the following error:
(You don't have access to licensing data for App ID: xxxxyyyzzzzz)
I have the following evidences:
If I use a token got from the Chrome Extension using chrome.identity.getAuthToken() the call is ok
If I run the same script inside the Options page of the Chrome Extension, I get the same error
A specific Chrome WebStore API actually work (the get items API)
I guess for some reason Chrome WebStore APIs are not accessible using a token produced outside a specific context (i.e. Chrome extension subject of the call).
Does anyone have evidence of this? Google team are you there :) ?

Java EE Container based Certificate authentication logout

In our Java EE application we use container based certificate authentication. We have created JAASLoginModule, which implements LoginModule interface with all required methods. We have configured our Wildfly and TomEE server to use this module both for authentication and ssl channel security, and everything goes smoothly with user login:
the user opens the browser and the app;
selects a certificate;
a JSF session is created, and now he is logged in;
A different story is with the logout. Just destroying the JSF session is not enough - after logout, if you just click back, the browser will get the certificate info from cache, recreate a session and lets you do the same stuff. Sometimes even browser restart does not help.
I could not find an effective way to call the logout method from the LoginModule from the JSF managed bean.
Any way to solve this problem?
Your problem is directly with the browser, so what you need is to tell the browser to "restart" the cache from your page every time it logs out, this, in order for it to think it's the first time the client is trying to get into that page. Kind of the same that private windows in Chrome and Firefox do.
Try this code:
//...
response.setHeader("Cache-Control","no-cache"); //Forces caches to obtain a new copy of the page from the origin server
response.setHeader("Cache-Control","no-store"); //Directs caches not to store the page under any circumstance
response.setDateHeader("Expires", 0); //Causes the proxy cache to see the page as "stale"
response.setHeader("Pragma","no-cache"); //HTTP 1.0 backward compatibility
//can check userId or something likes this.In this sample, i checked with userName.
String userName = (String) session.getAttribute("User");
if (null == userName) {
request.setAttribute("Error", "Session has ended. Please login.");
RequestDispatcher rd = request.getRequestDispatcher("login.jsp");
rd.forward(request, response);
}
Source: How to clear browser cache using java

NetSuite - Check if user is properly logged

I have a little question. I am working with NetSuite eCommerce and I need to check something, my site runs a script when user is logged, but sometimes it asks for a login even when still getting NetSuite Attributes. Something like this:
var loginEmail = "<%=getCurrentAttribute('customer','email')%>";
if(loginEmail==null || loginEmail=="") {
$("#cart").hide();
}
else {
$("#cart").show();
}
Do you know a specific NetSuite attribute or tag that I should be calling/using?
User sessions do time out after a period of inactivity, and user sessions are tracked with a cookie.
Try testing with a different browser - ie run NetSuite in FireFox and test the eCommerce functionality in Chrome or Safari, for instance.
Try nlapiGetLogin(). From NetSuite Help:
nlapiGetLogin
Returns the NetSuite login credentials of currently logged-in user.
This API is supported in user event, portlet, Suitelet, RESTlet, and SSP scripts. For information about the unit cost associated with this API, see API Governance.
Returns nlobjLogin
Since Version 2012.2
Example
This example shows how to get the credentials of the currently logged-in user.
//Get credentials of currently logged-in user
var login = nlapiGetLogin();
It doesn't say, but my thought is that this would return null if no user is logged in.
Use this code:
<%
var shoppingSession = nlapiGetWebContainer().getShoppingSession();
if (!shoppingSession.isLoggedIn())
$("#cart").hide();
else
$("#cart").show();
%>
In place of
<%=getCurrentAttribute('customer','email')%>
try using
<%=getCurrentAttribute('customer','entityid')%>

Resources