使用Worklight 6.1进行基本身份验证后发现了后端服务

时间:2014-05-04 20:41:10

标签: authentication adapter ibm-mobilefirst

我尝试为Web服务请求实现基本身份验证。在Worklight 6.1.0.1中,我使用后端发现自动生成适配器。

用例如下:用户输入用户名和密码,用于通过适配器连接到Web服务。

使用soapui和基本身份验证,请求可以正常工作。

我尝试使用安全质询进行身份验证,但是当我请求适配器时,我有以下响应。

“[警告]身份验证错误:无法应对任何这些挑战:{basic = WWW-Authenticate:BASIC realm =”tririga.com“}”

在authenticationConfig.xml文件下面:


<?xml version="1.0" encoding="UTF-8"?>
<tns:loginConfiguration xmlns:tns="http://www.worklight.com/auth/config" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">


<!-- Uncomment the next element to protect the worklight console and the first section in securityTests below. -->
 <staticResources>

    <resource id="subscribeServlet" securityTest="SubscribeServlet">
        <urlPatterns>/subscribeSMS*;/receiveSMS*</urlPatterns>
    </resource>
</staticResources> 


 <securityTests>

    <customSecurityTest name="SubscribeServlet">
        <test realm="SubscribeServlet" isInternalUserID="true"/>
    </customSecurityTest>    

    <customSecurityTest name="SingleStepAuthAdapter-securityTest">
        <test isInternalUserID="true" realm="tririga.com"/>
    </customSecurityTest>   

</securityTests> 

<realms>
    <realm name="SampleAppRealm" loginModule="StrongDummy">
        <className>com.worklight.core.auth.ext.FormBasedAuthenticator</className>
    </realm>

    <realm name="WorklightConsole" loginModule="requireLogin">
        <className>com.worklight.core.auth.ext.FormBasedAuthenticator</className>
        <onLoginUrl>/console</onLoginUrl>
    </realm>

    <realm loginModule="AuthLoginModule" name="tririga.com">
        <className>com.worklight.integration.auth.AdapterAuthenticator</className>
        <parameter name="login-function" value="SingleStepAuthAdapter.onAuthRequired"/>
        <parameter name="logout-function" value="SingleStepAuthAdapter.onLogout"/>
    </realm>

    <realm name="SubscribeServlet" loginModule="rejectAll">
<className>com.worklight.core.auth.ext.HeaderAuthenticator</className>          
    </realm>

    <!-- For websphere -->

</realms>

<loginModules>
    <loginModule name="AuthLoginModule">
        <className>com.worklight.core.auth.ext.NonValidatingLoginModule</className>
    </loginModule>

    <loginModule name="StrongDummy">
        <className>com.worklight.core.auth.ext.NonValidatingLoginModule</className>
    </loginModule>

    <loginModule name="requireLogin">
        <className>com.worklight.core.auth.ext.SingleIdentityLoginModule</className>
    </loginModule>

    <loginModule name="rejectAll">
        <className>com.worklight.core.auth.ext.RejectingLoginModule</className>
    </loginModule>

</loginModules>

我的适配器SoapAdapter1.js

function submitAuthentication(username, password){

    var userIdentity = {
            userId: username,
            displayName: username, 

    };

    WL.Server.setActiveUser("tririga.com", userIdentity);

    return { 
        authRequired: false 
    };

}

function TririgaWS_runDynamicQuery(params, headers){
var soapEnvNS;

soapEnvNS = 'http://www.w3.org/2003/05/soap-envelope';
var request = buildBody(params, 'null', soapEnvNS);
return invokeWebService(request, headers);
}


function TririgaWS_getActionItems(params, headers){
var soapEnvNS;

soapEnvNS = 'http://www.w3.org/2003/05/soap-envelope';
var request = buildBody(params, 'null', soapEnvNS);
return invokeWebService(request, headers);
}

function buildBody(params, namespaces, soapEnvNS){
var body =
    '<soap:Envelope xmlns:soap="' + soapEnvNS + '">\n' +
    '<soap:Body>\n';

body = jsonToXml(params, body, namespaces);

body += 
    '</soap:Body>\n' +
    '</soap:Envelope>\n';
return body;
}

function getAttributes(jsonObj) {
var attrStr = '';
for(var attr in jsonObj) {
    var val = jsonObj[attr];
    if (attr.charAt(0) == '@') {
        attrStr += ' ' + attr.substring(1);
        attrStr += '="' + val + '"';
    }
}
return attrStr;
}

function jsonToXml(jsonObj, xmlStr, namespaces) {
var toAppend = '';
for(var attr in jsonObj) {
    var val = jsonObj[attr];
    if (attr.charAt(0) != '@') {
        toAppend += "<" + attr;
        if (typeof val  === 'object') {
            toAppend += getAttributes(val);
            if (namespaces != null)
                toAppend += ' ' + namespaces;
            toAppend += ">\n";
            toAppend = jsonToXml(val, toAppend);
        }
        else {
            toAppend += ">" + val;
        }
        toAppend += "</" + attr + ">\n";
    }
}
return xmlStr += toAppend;
}


function invokeWebService(body, headers){

var input = {
    method : 'post',
    returnedContentType : 'xml',
    path : '/tririga/ws/TririgaWS',

    body: {
        content : body.toString(),
        contentType : 'text/xml; charset=utf-8'
    }

};

//Adding custom HTTP headers if they were provided as parameter to the procedure call 
headers && (input['headers'] = headers);

return WL.Server.invokeHttp(input);
}

此处包含身份验证功能的文件

var singleStepAuthRealmChallengeHandler = WL.Client.createChallengeHandler("tririga.com");

singleStepAuthRealmChallengeHandler.isCustomResponse = function(response) {
if (!response || !response.responseJSON || response.responseText === null) {
    return false;
}
if (typeof(response.responseJSON.authRequired) !== 'undefined'){
    return true;
} else {
    return false;
}
};

singleStepAuthRealmChallengeHandler.handleChallenge = function(response){
var authRequired = response.responseJSON.authRequired;

};


$("#loginBtn").bind('click', function () {
var username = $("#loginUsername").val();
var password = $("#loginPwd").val();


alert(username);
var invocationData = {
    adapter : "SoapAdapter1",
    procedure : "submitAuthentication",
    parameters : [ username, password ]
};

singleStepAuthRealmChallengeHandler.submitAdapterAuthentication(invocationData, {});

var invocationData = {
        adapter : "SoapAdapter1",
        procedure : "TririgaWS_getActionItems",
        parameters : [ '', '' ]
    };

WL.Client.invokeProcedure(invocationData, {
    onSuccess: getConnectionOK, 
    onFailure: getConnectionFAIL
}); 
});

function getConnectionOK(response){
WL.logger(JSON.stringify(response.invocationResult));
}

function getConnectionFAIL(response){
WL.logger(JSON.stringify(response.invocationResult));
}

使用适配器请求Web服务的基本身份验证的最佳方法是什么?

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

可能不是最好的方法,但解决方法是使用JavaScript创建SOAP Envelope(而不是后端发现)并在标头中插入基本的Authentification编码参数。

例如,适配器js中的过程getActions

function getActions(username,password) {

var b64Auth = org.apache.commons.codec.binary.Base64.encodeBase64String(new java.lang.String(username+':'+password).getBytes());
var bAuth = "Basic " + b64Auth;


var request =  
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:ws="http://ws.tririga.com">
<soap:Header/>
<soap:Body>
    <ws:getActionItems/>
</soap:Body>
</soap:Envelope>;

WL.Logger.debug("SOAP Request " + request);

var input = {
        method : 'post',
        returnedContentType : 'plain',
        path : '/tririga/ws/TririgaWS',
        headers: { Authorization: bAuth },
        body: {
             content: request.toString(),
             //contentType: 'application/soap+xml; charset=utf-8',
             contentType: 'text/xml; charset=utf-8',
            },

};

return WL.Server.invokeHttp(input);
}

对于这种情况,您不需要为身份验证实施安全性质询。