IBM worklight: Error with setActiveUser() while invoking adapter - ibm-mobilefirst

I am getting a strange exception on worklight server stating Procedure invocation error. Illegal State: Cannot change identity of an already logged in user in realm 'SingleStepAuthRealm'. The application must logout first. I am implementing Adapter Authentication using Single step. Posting all codes please help me to understand where i am messing up.
************************************SingleStepAuthAdapter-impl.js***************************
function onAuthRequired(headers, errorMessage){
WL.Logger.debug("Inside adapter.js onAuthRequired");
errorMessage = errorMessage ? errorMessage : null;
return {
authRequired: true,
errorMessage: errorMessage
};
}
function loginAuthentication(username, password,returnvalue){
WL.Logger.debug("Inside loginAuthentication");
var returned = WL.Server.invokeSQLStoredProcedure({
procedure : "loginAuthentication",
parameters : [username,password,returnvalue]
});
var isAuth = (returned.resultSet[0].returnvalue == 1);
if (isAuth){
//WL.Logger.debug("Inside loginAuthentication Authentication Successful "+JSON.stringify(WL.Server.getActiveUser("SingleStepAuthRealm")));
var userIdentity = {
userId: username,
displayName: username
};
WL.Server.setActiveUser("SingleStepAuthRealm", userIdentity);
return {
authRequired: false
};
WL.Logger.debug("Inside loginAuthentication Authentication Successful returned authRequired false");
}
return onAuthRequired(null, "Invalid Login Credentials");
}
function getSecretData(){
WL.Logger.debug("Inside adapter.js getSecretData");
return {
secretData: "Authentication Done and its a secret data"
};
}
function onLogout(){
WL.Logger.debug("Inside adapter.js onLogout");
WL.Server.setActiveUser("SingleStepAuthRealm", null);
WL.Logger.debug("Logged out");
}
*************************************SingleStepAuthRealmChallengeProcessor.js***********
var singleStepAuthRealmChallengeHandler = WL.Client.createChallengeHandler("SingleStepAuthRealm");
singleStepAuthRealmChallengeHandler.isCustomResponse = function(response) {
console.log("Inside singleStepAuthRealmChallengeHandler.isCustomResponse "+response +" :: "+ !response.responseJSON +" :: "+ response.responseText);
if (!response || !response.responseJSON ||
response.responseText === null) {
return false;
}
console.log("Inside response.responseJSON.authRequired "+response.responseJSON.authRequired);
if (typeof(response.responseJSON.authRequired) !== 'undefined'){
return true;
} else {
return false;
}
};
singleStepAuthRealmChallengeHandler.handleChallenge = function(response){
var authRequired = response.responseJSON.authRequired;
WL.Logger.debug("Inside singleStepAuthRealmChallengeHandler.handleChallenge :: response.responseJSON.authRequired ");
/*if(WL.Client.isUserAuthenticated("SingleStepAuthRealm") == false)
{
WL.Client.logout("SingleStepAuthRealm");
}*/
if (authRequired == true){
WL.Logger.debug(" Inside authRequired == true");
// 1.b else display up login screen
console.log("Login Returned false");
alert("Already Registered, Please login to continue");
$("#pagePort").load(path + "pages/Login.html", function()
{
$.getScript(path+ "js/Login.js",function() {
if (currentPage.init)
{
currentPage.init();
}
});
//$.getScript(path+ "js/SingleStepAuthRealmChallengeProcessor.js",function() {});
});
if (response.responseJSON.errorMessage)
{
alert("Problem "+response.responseJSON.errorMessage);
}
}
else if (authRequired == false)
{
WL.Logger.debug(" Inside authRequired == false "+WL.Client.isUserAuthenticated("SingleStepAuthRealm"));
var userName = "Random";//loginResultArr[0].json.uName;
console.log("Username "+ userName);
// 1.a if login data exists directly go to home page see
console.log("Login Returned true");
appUsernameGlobal = userName;
$("#pagePort").load(path+ "pages/MainMenu.html",function() {
$.getScript(path+ "js/MainMenu.js", function() {
if (currentPage.init) {
currentPage.init();
}
});
});
singleStepAuthRealmChallengeHandler.submitSuccess();
}
};
function loginClick() {
WL.Logger.debug(" Inside AuthSubmitButton");
var username = $("#init-username").val();
var password = $("#init-password").val();
var returnvalue = 0;
var invocationData = {
adapter : "SingleStepAuthAdapter",
procedure : "loginAuthentication",
parameters : [username, password,returnvalue]
};
WL.Logger.debug(" before submitAdapterAuthentication");
singleStepAuthRealmChallengeHandler.submitAdapterAuthentication(invocationData, {onSuccess: getLoginAuthenticationOK, onFailure: getLoginAuthenticationFAIL});
WL.Logger.debug(" after submitAdapterAuthentication");
}
function getLoginAuthenticationOK(response){
WL.Logger.debug("Inside SingleStepAuthenticationRealmChallenge.js getLoginAuthenticationOK :: secret data is :: " + JSON.stringify(response.invocationResult));
}
function getLoginAuthenticationFAIL(response){
WL.Logger.debug("Inside SingleStepAuthenticationRealmChallenge.js getLoginAuthenticationFAIL "+JSON.stringify(response.invocationResult));
}
*****************************SingleStepAuthAdapter.xml********************************
<?xml version="1.0" encoding="UTF-8"?>
<wl:adapter name="SingleStepAuthAdapter"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:wl="http://www.worklight.com/integration"
xmlns:sql="http://www.worklight.com/integration/sql">
<displayName>SingleStepAuthAdapter</displayName>
<description>SingleStepAuthAdapter</description>
<connectivity>
<connectionPolicy xsi:type="sql:SQLConnectionPolicy">
<dataSourceDefinition>
<driverClass>com.mysql.jdbc.Driver</driverClass>
<url>jdbc:mysql://192.168.xx.xx:3306/project</url>
<user>root</user>
<password>root</password>
</dataSourceDefinition>
</connectionPolicy>
<loadConstraints maxConcurrentConnectionsPerNode="10" />
</connectivity>
<procedure name="loginAuthentication"/>
<procedure name="getSecretData" securityTest="SingleStepAuthAdapter-securityTest"/>
</wl:adapter>
In Worklight - How to check if a client is already logged in, then pass the login screen its said to setActive user as null but setting null before provokes Server to go in infinite loop. And i want to understand if i am not setting any active user than why server saying the app must logout first ? I tried my level best but not getting my problem's soln.
{"errors":["Illegal State: Cannot change identity of an already logged in user in realm 'SingleStepAuthRealm'. The application must logout first."],"isSuccessful":false,"warnings":[],"info":[]}

I had files i.e. Registration.html, Login.html and Index.html. Here, I had included "SingleStepAuthRealmChallengeProcessor.js" in all of the file like <script src="js/ SingleStepAuthRealmChallengeProcessor.js"></script>
So, just to try different I removed this from Registration.html and Login.html files ONLY and re-ran this. And it worked like charm.
It may be inclusion of this SingleStepAuthRealmChallengeProcessor.js file was sending request to server at random and server was not expecting it and returned Illegal State: Cannot change identity of an already logged in user.
Just now i came to know via IBM techical guy that js references needs to be done only # Index.html

Related

Navigation guard keeps looping

I have a guard for my routes which does work in all aspects apart from when I wish to check a permissions object related to that page prior to continuing onto the url.
I have separated out the logic for the permissions check into a function and console logging it out all elements are working, in that it finds the right object in the array, finds the right key and value, and allows or blocks accordingly.
My problem though is that when I go through this route hitting this function it loops endlessly and crashes the browser. I think my overarching logic is fine but have I screwed up its implementation somewhere?
function guard (to, from, next) {
var loggedin_state = store.state.user.auth.loggedin // Boolean
var user = store.state.user.user // Array
var token = store.state.user.auth.token // String
var entryUrl // String
if(entryUrl == null || entryUrl == undefined){
entryUrl = to.path
}
if(loggedin_state == true) {
// Is the user profile blank
if(user == null) {
this.$store.dispatch('user/get_user_information', null)
}
// If they tried a route before logging in that would have been stored
if(entryUrl) {
// Store the url before wiping it
let url = entryUrl;
// Wipe the entry url variable
entryUrl = null;
// Carry on to permission checking function
return go_to_url(url);
} else {
// Go to stored url
return next(to.path)
}
} else {
// Is there a token assigned? If so they are approved and just need the profile information
if(token !== null) {
loggedin_state = true
this.$store.dispatch('user/get_user_information', null)
return go_to_url(to.path);
} else {
// Store entry url before redirect for use after login
entryUrl = to.path
// Re-route to login page
return next("/login");
}
}
function go_to_url(url) {
// Find matching object in user.permissions based upon url
var view_permissions = [
{ "area": "all", "read": 1, "create": 0, "edit": 0, "delete": 0 },
{ "area": "dashboard", "read": 1, "create": 0, "edit": 0, "delete": 0 }
];
// var view_permissions = store.state.user.permissions
var view_permission = view_permissions.find(view => view.area === to.name);
if(view_permission.read == 1) {
// Go to url
next(url);
} else {
// Re-route to somewhere
}
};
};
My problem was in passing a value to the next() function call. By removing that out it worked alright:
function guard (to, from, next) {
console.log('To:')
console.log(to)
console.log('From:')
console.log(from)
console.log('EntryUrl: ' + entryUrl)
// 1 - If no entry path was provided then set to
if(entryUrl == null || entryUrl == undefined){
entryUrl = to.path
console.log('EntryUrl: ' + entryUrl)
}
// 2 - Check if the user is marked as being logged in
var loggedin_state = store.state.user.auth.loggedin
if(loggedin_state == undefined) {
store.commit('user/set_delete_session', null)
return next("/login");
}
// 3 - If they are marked as logged in continue
var user = store.state.user.user
var token = store.state.user.auth.token
if(loggedin_state == true) {
// If the user isn't authorised with a token then send them to the log in page
if(token == null) {
store.commit('user/set_delete_session', null)
return next("/login");
}
// If they've got a token but no user profile data acquire it
if(user == null) {
UserApi.get_user_information(response.data.token)
.then(response => {
store.commit('user/set_user', response.data)
})
}
// If they tried a route before logging in that would have been stored
if(entryUrl) {
console.log('Go to saved URL')
// Store the url before wiping it
let url = entryUrl;
// Wipe the entry url variable
entryUrl = null;
// Go to stored url
return go_to_url(url);
} else {
console.log('Go to pointed url')
// Carry on to permission checking function
return go_to_url(to.path);
}
} else {
// The user is not logged in. Store the URL they were trying to visit and redirect them to the login page
entryUrl = to.path
console.log('EntryUrl: ' + entryUrl)
return next("/login");
}
function go_to_url(url) {
console.log(url)
// 1 - Grab the user permissions from the user profile
var permissions_array = null
if(user !== null) {
permissions_array = user.permissions
}
console.log(permissions_array)
// 2 - Check and route
if(permissions_array !== null) {
// Find the relevant permission object based upon the route name and the area key
var view_permissions = permissions_array.find(view => view.area === to.name);
console.log(view_permissions)
// If a permission object was found check its status, if no object found assume it is okay to view
if(view_permissions !== undefined) {
// If set to 1 the user can view this route, else reroute to a permissions denied page
if(view_permissions.read == 1) {
// Go to url
console.log('GUARD - PROCEED')
console.log(to.name)
next();
} else {
console.log('GUARD - BLOCKED')
return next("/permission-denied");
}
} else {
return next()
}
}
};
};

Node JS code not running in order

I have no idea why the code do not run as I expected.
When the UserExist is called, it should either console.log one of the statements that I set in my function code.
But the result is like the following the picture. Apreciate that if somebody can help!!
Console
var sql = require('mssql');
var config = require('./configuration/sqlconfig');
var Username = "Testing";
sql.connect(config);
console.log("Connected to DB");
if (!UserExist(Username)) {
InsertNewRecord(Username);
}
function isEmptyObject(obj) {
return !Object.keys(obj).length;
}
// This should work both there and elsewhere.
function isEmptyObject(obj) {
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
return false;
}
}
return true;
}
function UserExist(Username) {
console.log('Checking whether user exists or not... ');
new sql.Request().query("SELECT * FROM dbo.DB_Users WHERE Username = '" + Username + "';")
.then(function (recordset) {
if (isEmptyObject(recordset)) {
console.log("The User does not exist, ready to insert");
return true;
} else {
console.log("The user is existed already.");
return false;
}
}).catch(function (err) {
//When errors come
});
}
function InsertNewRecord(Username) {
console.log('Attempting to Insert records...');
new sql.Request().query("INSERT INTO dbo.Embright_Users (Username) VALUES ('" + Username + "');");
console.log("Added one new record");
}
The callbacks are not chained correctly. The InsertNewRecord() should be passed as callback to UserExist() function to make sure the execute in sequence. eg:
// Calling UserExist with a callback instead of 'if' statement
UserExist(Username, InsertNewRecord)
function UserExist(Username, callback) {
console.log('Checking whether user exists or not... ');
new sql.Request().query("SELECT * FROM dbo.DB_Users WHERE Username = '" + Username + "';")
.then(function (recordset) {
if (isEmptyObject(recordset)) {
console.log("The User does not exist, ready to insert");
// Calling InsertNewRecord with the username passed
callback(Username);
} else {
console.log("The user is existed already.");
// Do nothing
}
}).catch(function (err) {
//When errors come
});
}

Adal.js not setting props in localStorage

I'm having a problem using the adal.js library without Angular. (I'm using Vue.js.)
I have an authentication context instance, which is constructed with the following options (exact values have been changed to protect the innocent):
let config = {
tenant: '<tenant id>',
clientId: '<client id>',
redirectUri: 'http://myapplication.com/index.html',
// popUp: true,
cacheLocation: 'localStorage'
}
On my login page, I call authContext.login(), which redirects me first to https://login.microsoftonline.com/, where I log into AAD. Upon successful login, another redirect takes me back to my application, at the URI I've configured above, along with an id_token parameter in the URL. However, no token or other properties are stored by the library in local storage, just a few properties that are the result of the configuration.
On successful login, All I've got in localStorage is
{
adal.access.token.key: "",
adal.error: ""
adal.error.description: ""
adal.expiration.key: "0"
adal.idtoken: ""
adal.login.error: ""
adal.login.request: "http://myapplication.com/#/login"
adal.nonce.idtoken: "<a non-empty string>"
adal.session.state: ""
adal.state.login: "<a non-empty string>"
adal.token.keys: ""
adal.username: ""
}
So, as far as AAD is concerned, I've successfully authenticated, but the library itself seems to have no notion of what user is logged in, what tokens are associated with them, when the token expires, etc. Any advice on how to proceed would be most appreciated. Thank you in advance for reading.
Active Directory Authentication Library for JavaScript (ADAL JS) helps you to use Azure AD for handling authentication in your single page applications. This library is optimized for working together with AngularJS.
It will not save the tokens into the cache unless we code it. You can check the relative code from adal-angular.js. Here is a piece of code for your reference:
The saveTokenFromHash method will also save the tokens into cache and this function will execute after the page redirect back to the Angular app.
adal.js:
AuthenticationContext.prototype.saveTokenFromHash = function (requestInfo) {
this._logstatus('State status:' + requestInfo.stateMatch);
this._saveItem(this.CONSTANTS.STORAGE.ERROR, '');
this._saveItem(this.CONSTANTS.STORAGE.ERROR_DESCRIPTION, '');
// Record error
if (requestInfo.parameters.hasOwnProperty(this.CONSTANTS.ERROR_DESCRIPTION)) {
this._logstatus('Error :' + requestInfo.parameters.error);
this._logstatus('Error description:' + requestInfo.parameters[this.CONSTANTS.ERROR_DESCRIPTION]);
this._saveItem(this.CONSTANTS.STORAGE.FAILED_RENEW, requestInfo.parameters[this.CONSTANTS.ERROR_DESCRIPTION]);
this._saveItem(this.CONSTANTS.STORAGE.ERROR, requestInfo.parameters.error);
this._saveItem(this.CONSTANTS.STORAGE.ERROR_DESCRIPTION, requestInfo.parameters[this.CONSTANTS.ERROR_DESCRIPTION]);
if (requestInfo.requestType === this.REQUEST_TYPE.LOGIN) {
this._loginInProgress = false;
this._saveItem(this.CONSTANTS.STORAGE.LOGIN_ERROR, requestInfo.parameters.errorDescription);
} else {
this._renewActive = false;
}
} else {
// It must verify the state from redirect
if (requestInfo.stateMatch) {
// record tokens to storage if exists
this._logstatus('State is right');
if (requestInfo.parameters.hasOwnProperty(this.CONSTANTS.SESSION_STATE)) {
this._saveItem(this.CONSTANTS.STORAGE.SESSION_STATE, requestInfo.parameters[this.CONSTANTS.SESSION_STATE]);
}
var keys, resource;
if (requestInfo.parameters.hasOwnProperty(this.CONSTANTS.ACCESS_TOKEN)) {
this._logstatus('Fragment has access token');
// default resource
this._renewActive = false;
resource = this.config.loginResource;
if (!this._hasResource(resource)) {
keys = this._getItem(this.CONSTANTS.STORAGE.TOKEN_KEYS) || '';
this._saveItem(this.CONSTANTS.STORAGE.TOKEN_KEYS, keys + resource + this.CONSTANTS.RESOURCE_DELIMETER);
}
if (requestInfo.requestType === this.REQUEST_TYPE.RENEW_TOKEN) {
resource = this._getResourceFromState(requestInfo.stateResponse);
}
// save token with related resource
this._saveItem(this.CONSTANTS.STORAGE.ACCESS_TOKEN_KEY + resource, requestInfo.parameters[this.CONSTANTS.ACCESS_TOKEN]);
this._saveItem(this.CONSTANTS.STORAGE.EXPIRATION_KEY + resource, this._expiresIn(requestInfo.parameters[this.CONSTANTS.EXPIRES_IN]));
}
if (requestInfo.parameters.hasOwnProperty(this.CONSTANTS.ID_TOKEN)) {
this._loginInProgress = false;
this._user = this._createUser(requestInfo.parameters[this.CONSTANTS.ID_TOKEN]);
if (this._user && this._user.profile) {
if (this._user.profile.nonce !== this._getItem(this.CONSTANTS.STORAGE.NONCE_IDTOKEN)) {
this._user = null;
this._saveItem(this.CONSTANTS.STORAGE.LOGIN_ERROR, 'Nonce is not same as ' + this._idTokenNonce);
} else {
this._saveItem(this.CONSTANTS.STORAGE.IDTOKEN, requestInfo.parameters[this.CONSTANTS.ID_TOKEN]);
// Save idtoken as access token for app itself
resource = this.config.clientId;
if (!this._hasResource(resource)) {
keys = this._getItem(this.CONSTANTS.STORAGE.TOKEN_KEYS) || '';
this._saveItem(this.CONSTANTS.STORAGE.TOKEN_KEYS, keys + resource + this.CONSTANTS.RESOURCE_DELIMETER);
}
this._saveItem(this.CONSTANTS.STORAGE.ACCESS_TOKEN_KEY + resource, requestInfo.parameters[this.CONSTANTS.ID_TOKEN]);
this._saveItem(this.CONSTANTS.STORAGE.EXPIRATION_KEY + resource, this._user.profile.exp);
}
}
}
} else {
this._saveItem(this.CONSTANTS.STORAGE.ERROR, 'Invalid_state');
this._saveItem(this.CONSTANTS.STORAGE.ERROR_DESCRIPTION, 'Invalid_state');
if (requestInfo.requestType === this.REQUEST_TYPE.LOGIN) {
this._saveItem(this.CONSTANTS.STORAGE.LOGIN_ERROR, 'State is not same as ' + requestInfo.stateResponse);
}
}
}
};
And this function will be called in this.$get like below:
// special function that exposes methods in Angular controller
// $rootScope, $window, $q, $location, $timeout are injected by Angular
this.$get = ['$rootScope', '$window', '$q', '$location', '$timeout', function ($rootScope, $window, $q, $location, $timeout) {
var locationChangeHandler = function () {
var hash = $window.location.hash;
if (_adal.isCallback(hash)) {
// callback can come from login or iframe request
var requestInfo = _adal.getRequestInfo(hash);
_adal.saveTokenFromHash(requestInfo);
$window.location.hash = '';
if (requestInfo.requestType !== _adal.REQUEST_TYPE.LOGIN) {
_adal.callback = $window.parent.AuthenticationContext().callback;
}
// Return to callback if it is send from iframe
if (requestInfo.stateMatch) {
if (typeof _adal.callback === 'function') {
// Call within the same context without full page redirect keeps the callback
if (requestInfo.requestType === _adal.REQUEST_TYPE.RENEW_TOKEN) {
// Idtoken or Accestoken can be renewed
if (requestInfo.parameters['access_token']) {
_adal.callback(_adal._getItem(_adal.CONSTANTS.STORAGE.ERROR_DESCRIPTION), requestInfo.parameters['access_token']);
return;
} else if (requestInfo.parameters['id_token']) {
_adal.callback(_adal._getItem(_adal.CONSTANTS.STORAGE.ERROR_DESCRIPTION), requestInfo.parameters['id_token']);
return;
}
}
} else {
// normal full login redirect happened on the page
updateDataFromCache(_adal.config.loginResource);
if (_oauthData.userName) {
//IDtoken is added as token for the app
$timeout(function () {
updateDataFromCache(_adal.config.loginResource);
$rootScope.userInfo = _oauthData;
// redirect to login requested page
var loginStartPage = _adal._getItem(_adal.CONSTANTS.STORAGE.START_PAGE);
if (loginStartPage) {
$location.path(loginStartPage);
}
}, 1);
$rootScope.$broadcast('adal:loginSuccess');
} else {
$rootScope.$broadcast('adal:loginFailure', _adal._getItem(_adal.CONSTANTS.STORAGE.ERROR_DESCRIPTION));
}
}
}
} else {
// No callback. App resumes after closing or moving to new page.
// Check token and username
updateDataFromCache(_adal.config.loginResource);
if (!_adal._renewActive && !_oauthData.isAuthenticated && _oauthData.userName) {
if (!_adal._getItem(_adal.CONSTANTS.STORAGE.FAILED_RENEW)) {
// Idtoken is expired or not present
_adal.acquireToken(_adal.config.loginResource, function (error, tokenOut) {
if (error) {
$rootScope.$broadcast('adal:loginFailure', 'auto renew failure');
} else {
if (tokenOut) {
_oauthData.isAuthenticated = true;
}
}
});
}
}
}
$timeout(function () {
updateDataFromCache(_adal.config.loginResource);
$rootScope.userInfo = _oauthData;
}, 1);
}
...
And here is a sample code which could save the tokens into cache for your reference:
<html>
<head>
<script src="https://unpkg.com/vue"></script>
<script src="node_modules\adal-angular\lib\adal.js"> </script>
<script src="config.js"> </script>
</head>
<body>
<div>
<button onclick="login()" >Login</button>
</div>
<script>
var authContext=new AuthenticationContext(config);
function login(){
authContext.login();
}
function init(configOptions){
if (configOptions) {
// redirect and logout_redirect are set to current location by default
var existingHash = window.location.hash;
var pathDefault = window.location.href;
if (existingHash) {
pathDefault = pathDefault.replace(existingHash, '');
}
configOptions.redirectUri = configOptions.redirectUri || pathDefault;
configOptions.postLogoutRedirectUri = configOptions.postLogoutRedirectUri || pathDefault;
// create instance with given config
} else {
throw new Error('You must set configOptions, when calling init');
}
// loginresource is used to set authenticated status
updateDataFromCache(authContext.config.loginResource);
}
var _oauthData = { isAuthenticated: false, userName: '', loginError: '', profile: '' };
var updateDataFromCache = function (resource) {
// only cache lookup here to not interrupt with events
var token = authContext.getCachedToken(resource);
_oauthData.isAuthenticated = token !== null && token.length > 0;
var user = authContext.getCachedUser() || { userName: '' };
_oauthData.userName = user.userName;
_oauthData.profile = user.profile;
_oauthData.loginError = authContext.getLoginError();
};
init(config);
function saveTokenFromHash(){
var hash = window.location.hash;
var requestInfo = authContext.getRequestInfo(hash);
if (authContext.isCallback(hash)) {
// callback can come from login or iframe request
var requestInfo = authContext.getRequestInfo(hash);
authContext.saveTokenFromHash(requestInfo);
window.location.hash = '';
if (requestInfo.requestType !== authContext.REQUEST_TYPE.LOGIN) {
authContext.callback = window.parent.AuthenticationContext().callback;
}
}
}
saveTokenFromHash();
</script>
</body>
</html>

WL.Server.getActiveUser returns Null

I need the ability to get a users login userid/password in a java adapter. After reading lots of articles, the best way seems to be to call
WL.Server.getActiveUser from a javascript function that gets called from the java adapter. So, I added a getIdentity function to the http adapter that authenticates our app. I have verified that getActiveUser works in the authentication function that the login pages calls...
When I call the getIdentity function, getActiveUser returns null using The same authentication realm. I have set the realm in the application_descriptor file. Not sure what else I have to do. Any ideas?
function performAuthentication(username, password) {
WL.Logger.info("In performAuthentication: username = " + username + " password = " + password + "Time = " + new Date(new Date().getTime()).toLocaleString());
var invocationData = {
adapter : 'BluePages',
procedure : 'authenticate',
parameters : [username, password]
};
var invocationResult = WL.Server.invokeProcedure(invocationData);
var fullName = invocationResult.result.fullName;
if (invocationResult.result.success == false) {
return {
authRequired: true,
loginPassed: false
};
}
else {
userIdentity = {
userId: username,
credentials: password,
displayName: username,
attributes: {
foo: "bar"
}
};
WL.Server.setActiveUser("AuthRealm", null);
WL.Server.setActiveUser("AuthRealm", userIdentity);
var activeUser = WL.Server.getActiveUser("AuthRealm");
WL.Logger.info("activeUser = " + activeUser);
if(activeUser && activeUser.userId == username){
WL.Logger.info("Active userId = " + activeUser.userId + " password = " + activeUser.credentials);
WL.Logger.info("User has been logged in!");
return {
loginPassed: true,
authRequired: false,
fullName: fullName,
result: invocationResult.result
};
}
else {
WL.Logger.info("Else Clause...");
if(activeUser != null)
WL.Server.setActiveUser("AuthRealm", null);
WL.Server.setActiveUser("AuthRealm", userIdentity);
}
return {
authRequired: false,
loginPassed: true,
fullName: fullName
};
}
}
function getIdentity() {
WL.Logger.info("AuthAdapter: In getIdentity: Time = " + new Date(new Date().getTime()).toLocaleString());
WL.Logger.info("AuthAdapter: userIdentity = " + userIdentity);
var activeUser = WL.Server.getActiveUser("AuthRealm");
WL.Logger.info("AuthAdapter: getIdentity: getActiveUser returned = " + activeUser);
if (activeUser) {
WL.Logger.info("AuthAdapter: getIdentity userId = " + activeUser.userId);
return {
userId: activeUser.userId,
credentials: activeUser.credentials,
};
}
}
There could be 2 reasons to get null when using WL.Server.getActiveUser:
1)If no realm is defined on the adapter, the method returns null (active user is unknown)
2)If a realm is defined on the adapter:
If there is no strong identity associated with the user (the user was authenticated in this session or in a previous session), the method returns null.
In your case you said the realm is exist so I suggest to try #2
You can find more information here:
https://www.ibm.com/support/knowledgecenter/SSZH4A_6.0.0/com.ibm.worklight.help.doc/apiref/r_method_wl_server_getactiveuser.html

login authentication in worklight

I referred to this question Login Authentication In IBM Worklight I have read all the pdfs but still my login is not working.I have used another method to check for the database.
var procedure1Statement = WL.Server.createSQLStatement("select t_id from teacher where
t_id=? and t_password=?");
var response;
function login(id,pass) {
response= WL.Server.invokeSQLStatement({
preparedStatement : procedure1Statement,
parameters : [id,pass]});
return response;
}
function submitAuthentication(id, pass){
var invocationData={
adapter : "admin",
procedure : " login",
parameters : [id,pass],
};
var result=WL.Server.invokeProcedure (invocationData);
if(result.t_id >1 )
{
var userIdentity = {
userId : id,
displayName : id,
attributes: {
role: "admin"
}
};
WL.Server.setActiveUser("adminRealm",userIdentity);
return{
authRequired : false
};
}
return onAuthRequired(null,"Invalid Login Credentials");
}
function onLogout(){
WL.Logger.debug("Logged Out");
}
What condition should I use here to make it work
if(result.t_id >1 )
if (result.resultSet.length == 1)
Or that plus whatever other checks you want to make on the returned record.
if (result.resultSet.length == 1 && result.resultSet[0].t_id > 0)
BTW:
You have a stray space in your invocationData before the procedure name:
procedure : " login",