adal javascript windows store app token - javascript

I have a javascript windows store app that is authenticathing with AAD via Microsoft.Preview.WindowsAzure.ActiveDirectory.Authentication library. It works against an ASP.NET WebAPI hosted in Azure. It works fine, it prompst the user to login (windows login service), once logged the user can work and is not asked to log in again. The problem I have found is that when the user does not use the app for a time, I´m not sure but I Think is between 20 and 30 minutes, the app gets iddle. It does not respond to user querys. I think comunication with webApi is lost, I'm not sure if the token acquired by the app is expired or Azure itself cuts the connection.
This is how I'm getting the token
var authcontext = new aal.AuthenticationContext(audience);
aal.DefaultTokenCache().clear();
return authcontext.acquireTokenAsync(resource, clientID, redirectUri.absoluteUri, "", null).then(function (result) {
if (aal.AuthenticationStatus.succeeded == result.status) {
accessToken = result.accessToken;
return true;
}
}
and the webApi call
var uri = new Windows.Foundation.Uri(apiUrl + apiName);
var httpClient = new Windows.Web.Http.HttpClient();
httpClient.defaultRequestHeaders.authorization =
new Windows.Web.Http.Headers.HttpCredentialsHeaderValue("Bearer", accessToken);
return httpClient.getAsync(uri).then(function (response) {
if (response.isSuccessStatusCode == true)
return response.content.readAsStringAsync().then(function (responseText) {
var array = JSON.parse(responseText);
return array;
});
else
{
var md = new Windows.UI.Popups.MessageDialog(response, "Error");
md.showAsync();
}
});
I`ve tried adding
<sessionTokenRequirement lifetime="96:00:00" /> and <cookieHandler persistentSessionLifetime="60.0:0:0" requireSsl="true" /> in the web.config but still getting the error.
I am trying unsuccesfully adding ADAL new releases to the project because I read something about refresh tokens, I'm working on it but don´t find any example for windows store apps.
Any clue about the cause of the problem and how to solve it??
Thanks for your time.

The library version you are using is ancient and not supported. Also, cookies play no part in the api communications.
I recommend switching to the latest stable ADAL. Windows Store sample using ADAL: https://github.com/AzureADSamples/NativeClient-WindowsStore

Related

OIDC client + Identity Server 4, setting max_age silent token reniew not working

I have an angular 10 application with OIDC JS client as open id connect. On browser or tab close I need to redirect the user back to the login page.
By setting max_age to the UserManager the functionality is working fine, however, silent token reniew is not working while using the application and it redirects to the login page. The token got expire.
const settings: any = await response.json();
settings.automaticSilentRenew = true;
settings.includeIdTokenInSilentRenew = true;
settings.accessTokenExpiringNotificationTime = 30; // default 60
settings.checkSessionInterval = 5000; // default 2000;
settings.silentRequestTimeout = 20000;// default: 10000
settings.monitorSession = true;
settings.loadUserInfo = true;
settings.filterProtocolClaims = true;
settings.max_age = 10;
settings.prompt="login"
this.userManager = new UserManager(settings);
public async completeSignIn(url: string): Promise<IAuthenticationResult> {
try {
await this.ensureUserManagerInitialized();
const user = await this.userManager.signinCallback(url);
this.userSubject.next(user);
return this.success(user && user.state);
} catch (error) {
console.log('There was an error signing in: ', error);
return this.error('There was an error signing in.');
}
}
While doing some search I found that prompt="login" should work, but not able to solve it. How can I achieve if the application is active the silent token reniew should work if they close the browser or tab prompt the login screen.
max_age=10 is saying "if the user interactively signed in more than 10 seconds ago then force interactive authentication". In short I don't think you want that as it effectively disables silent renewal and will cause the authorize endpoint to return error=login_required if prompt=none is specified (which it will be for silent renewal).
Using sessionStorage to store UserManager state should acheive what you want as this is tied to the browser window and will be automatically cleared up if the window/tab is closed or the browser closed.
This will not affect the user's session cookie on the IDP however so you'd still want to manually specify max_age=n or prompt=login when you are doing the interactive sign in (i.e. if no local client-side session currently exists). To do this you can pass additional params to signinRedirect rather than defining them at UserManager settings level:
await manager.signinRedirect({ prompt: "login" });
Additionally, since these params can be tampered with it's wise to also check the auth_time claim in your backend to ensure the user really did authenticate recently.
for this issue
On browser or tab close I need to redirect the user back to the login
page
you must switch from sessionStorage to localStorage,
new Oidc.UserManager({ userStore: new Oidc.WebStorageStateStore({ store: window.localStorage }) }).signinRedirectCallback().then(function () {
window.location.replace("./");});
please check this Page
For silent token refresh please check this Page
Setting only prompt and removing the max_age also solve the issue for me
settings.prompt="login"

PouchDB and React-Native not replicating .to() but .from() is working

For some reason documents created on my app are not showing up on my remote couchdb database.
I am using the following
import PouchDB from 'pouchdb-react-native'
let company_id = await AsyncStorage.getItem('company_id');
let device_db = new PouchDB(company_id, {auto_compaction: true});
let remote_db = new PouchDB('https://'+API_KEY+'#'+SERVER+'/'+company_id, {ajax: {timeout: 180000}});
device_db.replicate.to(remote_db).then((resp) => {
console.log(JSON.stringify(resp));
console.log("Device to Remote Server - Success");
return resp;
}, (error) => {
console.log("Device to Remote Server - Error");
return false;
});
I get a successful response the response:
{
"ok":true,
"start_time":"2018-05-17T15:19:05.179Z",
"docs_read":0,
"docs_written":0,
"doc_write_failures":0,
"errors":[
],
"last_seq":355,
"status":"complete",
"end_time":"2018-05-17T15:19:05.555Z"
}
When I go to my remote database, document_id's that am able to search and grab on the application do not show up.
Is there something I am not taking into account?
Is there anything I can do to check why this might be happening?
This worked when I used the same scripting method in Ionic and when I switched to React-Native I noticed this is the case.
NOTE: When I do .from() and get data from remote to the device, I get the data. For some reason it just isn't pushing data out
"Is there anything I can do to check why this might be happening?"
I would try switching on debugging as outlined here.
PouchDB.debug.enable('*');
This should allow you to view debug messages in your browser's JavaScript console.

Can't destroy AWS Cognito session from within React application

I'm trying to log out of my application that's using AWS Cognito by calling their logout endpoint. I'm not using the AWS SDK because as far as I can tell, it does not yet cover oauth app integrations and sign in using external federated identity providers (please correct me if I'm wrong about that). I log in from an AWS-hosted login screen that I'm redirected to when I call their authorization endpoint. They redirect me back to my page with a "code" which I post back to them using their token endpoint to get tokens. All of this is textbook oauth 2.0 stuff.
The problem is that when I call the logout endpoint using a JavaScript browser redirect (window.location.href = ....) it doesn't clear the cookies that are set when I logged in ("XSRF-TOKEN" and "cognito") and I can't manually clear them because they were set from the AWS domain which is different from the one where my site is hosted. The cookies do get cleared when I enter the logout link in the address bar. There's clearly a difference between using window.location.href in code and dropping a link in my address bar.
To clear out the sessoin you need to use clearCachecId() and then reset the Cognito Id credentials. This is my function using the AWS SDK:
import AWS from 'aws-sdk/global';
const getCurrentUser = () => {
const userPool = newCognitoUserPool({
UserPoolId: YOUR_USER_POOL_ID,
ClientId: YOUR_APP_CLIENT_ID
});
return userPool.getCurrentUser();
}
const signOutUser = () => {
const currentUser = getCurrentUser();
if (currentUser !== null) {
curentUser.signOut();
}
if (AWS.config.credentials) {
AWS.config.credentials.clearCachedId(); // this is the clear session
AWS.config.credentials = new AWS.CognitoIdentityCredentials({}); // this is the new instance after the clear
}
}
That should take care of that.
It's a timing issue involving the use of windows.location and cookies. It seems that I was causing the same cookie, XSRF-TOKEN, to be unset and then reset so fast that it was just not happening at all. Inserting a timeout between logging out and redirecting back to the log in screen fixes the problem. There are some guys on this thread who seem to know something about it: https://bytes.com/topic/javascript/answers/90960-window-location-cookies

Azure using wrong callback url during implicit flow login

I'm currently struggling with a weird problem in azure active directory implicit flow oauth authentication. I've implemented a spa webapp using msal.js to login users to their microsoft accont.
The userAgentApplication is executed as shown below:
userAgentApplication = new
Msal.UserAgentApplication(client_id,null,function(errorDes,token,error,tokenType)
{
if(error) {
console.log(JSON.stringify(error));
return;
}
},{ redirectUri: 'https://example.com/app/msalCallback.html' });
When they click login executing the is piece of code:
logInPopup = function() {
var uaa = userAgentApplication;
return new Promise(function(resolve,reject) {
uaa.loginPopup([
'https://graph.microsoft.com/user.read'
]).then(function(token) {
//signin success
console.log(token);
var user = uaa.getUser();
console.log(JSON.stringify(user));
resolve(user);
}, function(error) {
console.log(JSON.stringify(error));
reject(error);
});
})
}
The popup comes up and the user tries to login but the following error comes up:
Microsoft account is experiencing technical problems. Please try again later.
In the url the error parameters string is:
error_description=The provided value for the input parameter
'redirect_uri' is not valid The expected value is
'https://login.live.com/oauth20_desktop.srf' or a URL which matches
the redirect URI registered for this client application.
Upon further research I found that though I configured the redirect uri to be
https://example.com/app/msalCallback.html
(Which I confirmed on the application registration page to be true)
The redirect_uri of the /oauth2/v2.0/authorise url in the login popup page is:
redirect_uri=https://example.com/app/
Which is weird but the above uri is not random one. It is in fact the callback uri for a previous previously registered but now deleted app with the same name.
Further investigation showed that when I config Msal to use the old the redirect_uri login passes.
I'm fresh out of ideas. It looks like a bug in the azure network but wanted to know if anyone else has had this problem or at least point me in the right direction towards getting in contact with azure to find a fix.
Thanks in advance
I've found the cause of the problem after carefully reviewing the msal.js documentation i found that i was setting the redirectUri incorrectly. The correct way is as follows:
var userAgentApplication = new
Msal.UserAgentApplication(client_id,null,function(errorDes,token,error,tokenType)
{
if(error) {
console.log(JSON.stringify(error));
return;
}
});
userAgentApplication.redirectUri = 'https://example.com/app/msalCallback.html'
Hope that helps.
regards

Meteor login via Third party library

I'm trying to login to my meteor site via a third party library like this one:
https://gist.github.com/gabrielhpugliese/4188927
In my server.js i have:
Meteor.methods({
facebook_login: function (fbUser, accessToken) {
var options, serviceData, userId;
serviceData = {
id: fbUser.id,
accessToken: accessToken,
email: fbUser.email
};
options = {
profile: {
name: fbUser.name
}
};
userId = Accounts.updateOrCreateUserFromExternalService('facebook', serviceData, options);
return userId;
}, ......
In my client.js I have:
facebookLogin: function () {
if (Meteor.user())
return;
if (!Session.equals("deviceready", true))
return;
if (!Session.equals("meteorLoggingIn", false))
return;
// Do not run if plugin not available
if (typeof window.plugins === 'undefined')
return;
if (typeof window.plugins.facebookConnect === 'undefined')
return;
// After device ready, create a local alias
var facebookConnect = window.plugins.facebookConnect;
console.log('Begin activity');
Session.equals("meteorLoggingIn", true);
Accounts._setLoggingIn(true);
facebookConnect.login({
permissions: ["email", "user_about_me"],
appId: "123456789012345"
}, function (result) {
console.log("FacebookConnect.login:" + JSON.stringify(result));
// Check for cancellation/error
if (result.cancelled || result.error) {
console.log("FacebookConnect.login:failedWithError:" + result.message);
Accounts._setLoggingIn(false);
Session.equals("meteorLoggingIn", false);
return;
}
var access_token = result.accessToken;
Meteor.call('facebook_login', result, access_token, function (error, user) {
Accounts._setLoggingIn(false);
Session.equals("meteorLoggingIn", false);
if (!error) {
var id = Accounts._makeClientLoggedIn(user.id, user.token);
console.log("FacebookConnect.login: Account activated " + JSON.stringify(Meteor.user()));
} else {
// Accounts._makeClientLoggedOut();
}
});
});
}, // login
facebookLogout: function () {
Meteor.logout();
// var facebookConnect = window.plugins.facebookConnect;
// facebookConnect.logout();
},
The third party library (Facebook Android SDK in my case) works fine. My problem is after the "var id = Accounts._makeClientLoggedIn(user.id, user.token);" the Meteor.user() returns Undefined. However If I do a page refresh in the browser works fine and the template renders as a logged in user.
Anyone knows how to fix the 'Undefined' on client ??
PS. On server side the users collection looks fine. The meteor token and everything else are there.
Solved. I had to add : this.setUserId(userId.id);
after userId = Accounts.updateOrCreateUserFromExternalService('facebook', serviceData, options); at server.js
Meteor's client side javascript can't run fibers. Fibers allows synchronous code to be used with javascript since by design js is asynchronous. This means there are callbacks that need to be used to let you know when the task is complete.
From what it looks like Accounts._makeClientLoggedIn doesn't take a callback & unfortunately and doesn't return any data looking at its source. I can't say i've tried this myself because I can't test your code without the android sdk but have you tried using Deps.flush to do a reactive flush?
Also Meteor also has very clean and easy facbeook integration. If you simply add the facebook meteor package
meteor add accounts-facebook
You can get access to a lovely Meteor.loginWithFacebook method that can make everything reactive and your code simpler and really easy. If you need to modify it to use the Android SDK Dialog instead you can easily modify the code out as the code for the module is out there for you to hack up to your spec
Edit: If you're using an external SDK such as the java SDK/cordova plugin
Set your plugin so that it redirects to the following URL (set up for meteor.com hosting):
http://yourmeteorapp.meteor.com/_oauth/facebook?display=touch&scope=your_scope_request_params&state=state&code=yourOAuthCodeFromJava&redirect=YourAPP
So in the querystring we have:
scope= Contains your facebook scope params (for permissions)
code= Your OAuth code from the java sdk
redirect=Where to redirect to after once logged in instead of the window.close
state= A cros site forgery state value, any random value will do
This url is basically used to mimic would what be given to the REDIRECT_URI at : https://developers.facebook.com/docs/reference/dialogs/oauth/
This will redirect to meteor's OAuth helper (at https://github.com/meteor/meteor/blob/master/packages/accounts-oauth-helper/oauth_server.js)
So what would happen is you give the OAuth code from Java to meteor, it fetches the OAuth token and the user's data, then redirect the user to a URL in your app

Categories

Resources