IBM Worklight 5.0.6 - для входа требуется два клика вместо одного
Я использую аутентификацию на основе форм и обработчик вызовов (примеры кодов) в своем приложении. Проблема в том, что это не аутентификация пользователей одним нажатием на кнопку входа в систему - мне нужно нажать два раза. Зачем?
Я защитил все функции адаптера.
Мой обработчик вызова:
var myAppRealmChallengeHandler = WL.Client.createChallengeHandler("myAppRealm");
myAppRealmChallengeHandler.isCustomResponse = function(response) {
if (!response || response.responseText === null) {
return false;
}
var indicatorIdx = response.responseText.search('j_security_check');
WL.Logger.debug("indicatorIdx =" + indicatorIdx);
if (indicatorIdx >= 0){ return true; }
return false;
};
myAppRealmChallengeHandler.handleChallenge = function(response) {
$.mobile.changePage("#landingPage" , { transition: "slide"});
WL.Logger.debug("Login Again");
};
myAppRealmChallengeHandler.submitLoginFormCallback = function(response) {
var isLoginFormResponse = myAppRealmChallengeHandler.isCustomResponse(response);
WL.Logger.debug("submitLoginFormCallback " + isLoginFormResponse + " responseText " + response.responseText);
if (isLoginFormResponse){
myAppRealmChallengeHandler.handleChallenge(response);
} else {
myAppRealmChallengeHandler.submitSuccess();
}
};
$('#logindone').bind('click', function () {
var reqURL = '/j_security_check';
var options = {};
options.parameters = {
j_username : $.trim($('#fldloginUserID').val().toLowerCase()),
j_password : $.trim($('#fldloginUserPassword').val())
};
options.headers = {};
myAppRealmChallengeHandler.submitLoginForm(reqURL, options, myAppRealmChallengeHandler.submitLoginFormCallback);
processLogin();
});
authenticationConfig.xml
<securityTests>
<mobileSecurityTest name="myMobileSecurity">
<testUser realm="myAppRealm"/>
<testDeviceId provisioningType="none"/>
</mobileSecurityTest>
<customSecurityTest name="PushApplication-custom-securityTest">
<test isInternalUserID="true" realm="PushAppRealm"/>
</customSecurityTest>
<customSecurityTest name="myAppSecurityTestCustom">
<test isInternalUserID="true" realm="myAppRealm"/>
</customSecurityTest>
<customSecurityTest name="WorklightConsole">
<test realm="WorklightConsole" isInternalUserID="true"/>
</customSecurityTest>
</securityTests>
<realms>
<realm loginModule="StrongRC" name="myAppRealm">
<className>com.worklight.core.auth.ext.FormBasedAuthenticator</className>
<!--<parameter name="login-page" value="login.html"/>-->
</realm>
<realm loginModule="PushAppLoginModule" name="PushAppRealm">
<className>com.worklight.core.auth.ext.BasicAuthenticator</className>
<parameter name="basic-realm-name" value="PushAppRealm"/>
</realm>
<realm loginModule="Console" name="WorklightConsole">
<className>com.worklight.core.auth.ext.FormBasedAuthenticator</className>
<onLoginUrl>/console</onLoginUrl>
</realm>
</realms>
<loginModules>
<loginModule name="PushAppLoginModule">
<className>com.rc.services.RCAuthModule</className>
</loginModule>
<loginModule name="StrongRC">
<className>com.worklight.core.auth.ext.NonValidatingLoginModule</className>
</loginModule>
<loginModule name="Console">
<className>com.worklight.core.auth.ext.SingleIdentityLoginModule</className>
</loginModule>
</loginModules>
моя функция processLogin()
function processLogin(userid,password){
var userid = $("#fldloginUserID").val();
var password = $("#fldloginUserPassword").val();
WL.Logger.debug("Authenticating user credentials...");
var invocationData = { adapter: "LDAPAdapter", procedure: "ValidateUsers", parameters: [userid, password]};
WL.Client.invokeProcedure(invocationData, {
onSuccess: checkUserAccountStatus,
onFailure: function(){ hideBusyIndicator();
showPopUp(msg_en.LoginFailed_MsgTitle , msg_en.LoginFailed_MsgDescription_2);
} ,timeout : 30000 });
}
function checkUserAccountStatus(response){
WL.Logger.debug("Checking user account status...");
xmlDoc = $.parseXML(response.invocationResult.result);
$xml = $( xmlDoc );
if (!response ||!response.invocationResult || !response.invocationResult.result ||
$xml.find("isUserValidated").text()=="false" ) { hideBusyIndicator();
showPopUp(msg_en.LoginFailed_MsgTitle, msg_en.LoginFailed_MsgDescription_2);
else { getUserDetails(response.invocationResult.result); }
}
function getUserDetails($xml){
...doing something over retrieved data from LDAP ,like saving in local var......
....
...then calling another adapter....
if($xml.find("LDAPuserID").text() > 0){
var invocationData = {adapter: "MQAdapter",procedure: "ListSummariesDetails", parameters: [$xml.find("LDAPuserID").text() ] };
WL.Client.invokeProcedure(invocationData, {
onSuccess: getSecretSuccessData_Callback,
onFailure: function(){ hideBusyIndicator();
showPopUp(msg_en.SystemError_Title , msg_en.SystemError_Description);
} ,timeout : 30000 });
}
}
function getSecretSuccessData_Callback(response){
...... now do something over retrived data
...let the user go in the main page of the App after login screen
$.mobile.changePage("#mainPage" , { transition: "slide"});
}
Функции адаптера ValidateUsers и ListSummariesDetails защищены с помощью myAppSecurityTestCustom, который приведен выше.
3 ответа
На этот вопрос ответили через PMR, который клиент открыл в IBM. С тех пор они изменили реализацию на использование аутентификации на основе адаптера, поскольку это поток аутентификации, который соответствует структуре их приложения. Этот вопрос уже несколько устарел...
Похоже, ваша страница входа в систему (LandPage) видна при запуске приложения, и при первом нажатии на logindone аутентификация не выполняется (пока). Это не сработает так, как вы ожидаете.
Сделайте другую страницу страницей по умолчанию для вашего приложения. Возьмите вызов processLogin() из вашего обработчика кликов. Я бы также поместил переход к mainPage в случае успеха submitLoginFormCallback().
Теперь поместите вызов WL.Client.login() в wlCommonInit(). (это вызовет аутентификацию) Поместите вызов processLogin() в успешный обратный вызов для вызова WL.Client.login()
Я столкнулся с этой проблемой, когда я использовал IP-адрес для тестирования, и в коде присутствовала запись DNS, т.е. мой URL был mydomain.com, а IP - 123.123.123.123, теперь, если я создал приложение с использованием 123.123.123.123, я должен нажать кнопка входа дважды.
Решение, которое я нашел, состояло в том, чтобы добавить mydomain.com в мой сервер hosts / DNS, и после этого я создал приложение для mydomain.com.
Работал отлично для меня.