Android WCF服务用户名密码验证

时间:2018-03-23 13:01:04

标签: java android wcf authentication credentials

连接 经过身份验证 WCF 服务并使用 BasicHttpBinding < / EM>

C#(Visual Studio - 添加服务参考)

private void Show()
    {
        MobilServiceClient client = new MobilServiceClient();
        client.ClientCredentials.UserName.UserName = "admin";
        client.ClientCredentials.UserName.Password = "adminpass";
        MessageBox.Show(client.LoginServiceTest());
    }

此代码有效。但我无法将服务与java连接。

Ksoap2:

public static String WCFShow (String METHOD_NAME, int timeOut, List<KSoapParameters> parameters)  {

    SoapObject request = new SoapObject("http://tempuri.org/", "LoginServiceTest");
    for (int i =0;i<parameters.size();i++){
        request.addProperty(parameters.get(i).getKey(),parameters.get(i).getValue());
    }
    SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
    envelope.dotNet = true;
    List<HeaderProperty> header = new ArrayList<HeaderProperty>();
    header.add(new HeaderProperty("Authorization","Basic "+org.kobjects.base64.Base64.encode("admin:adminpass".getBytes())));
    envelope.setOutputSoapObject(request); 

    HttpTransportSE aht = new HttpTransportSE "https://xxx.xxx.com.tr/testBasicHttpBinding/MobilService.svc",timeOut); 
    aht.debug = true;

    try {
        aht.call("http://tempuri.org/IMobilService/"+ "LoginServiceTest", envelope, header); //            Object result = envelope.getResponse();
        Object result = envelope.bodyIn;

        resultData = result.toString();
        //Log.d("ERDINC", resultData.toString());
    } catch (IOException e) {
        e.printStackTrace();
        resultData="ERROR"+e.toString();
    } catch (XmlPullParserException e) {
        e.printStackTrace();
        resultData="ERROR"+e.toString();
    }

    return resultData;
}

的Apache:

public void ApacheSoap() {
    try {
        String body = "<v:Envelope xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:d=\"http://www.w3.org/2001/XMLSchema\" xmlns:c=\"http://schemas.xmlsoap.org/soap/encoding/\" xmlns:v=\"http://schemas.xmlsoap.org/soap/envelope/\">\n" +
                "<v:Header />" +
                "<v:Body>" +
                "<LoginServiceTest xmlns=\"http://tempuri.org/\" id=\"o0\" c:root=\"1\">" +
                "</LoginServiceTest>" +
                "</v:Body>" +
                "</v:Envelope>";
        StringEntity stringEntity = new StringEntity(body, "UTF-8");
        stringEntity.setChunked(true);

        HttpPost httpPost = new HttpPost("https://xxx.xxx.com.tr/testBasicHttpBinding/MobilService.svc”);
        httpPost.setEntity(stringEntity);
        httpPost.addHeader("Content-Type", "text/xml");
        httpPost.addHeader("SOAPAction", "http://tempuri.org/IMobilService/"+ "LoginServiceTest");

        DefaultHttpClient httpClient = new DefaultHttpClient();

        UsernamePasswordCredentials creds = new UsernamePasswordCredentials("admin", "adminpass");
        BasicScheme scheme = new BasicScheme();
        Header header = scheme.authenticate(creds,httpPost);
        httpPost.setHeader(header);

        HttpResponse response = httpClient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        String strResponse = null;
        if (entity != null) {
            strResponse = EntityUtils.toString(entity);
            Log.d("strResponse", strResponse);
        }

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (AuthenticationException e) {
        e.printStackTrace();
    }
}

我收到了错误。

SoapFault - faultcode: 'a:InvalidSecurity' faultstring: 'an error occurred when verifying security for the message.' faultactor: 'null' detail

安全模式= TransportWithMessageCredential

传输ClientCredentialType =基本

消息ClientCredentialType =用户名

绑定类型= BasicHttpBinding

的web.config

<?xml version="1.0"?>
<configuration>
  <appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true"/>
  </appSettings>
  <system.web>
<customErrors mode="Off"/>
<compilation strict="false" explicit="true" targetFramework="4.6.1" debug="true"/>
<httpRuntime targetFramework="4.5"/>
  </system.web>
  <system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<directoryBrowse enabled="true"/>
  </system.webServer>
  <system.serviceModel>
<bindings>
  <basicHttpBinding>
    <binding name="basicHttp" maxBufferSize="2147483647" maxReceivedMessageSize="2147483647">
      <security mode="TransportWithMessageCredential">
        <transport clientCredentialType="Basic"/>
        <message clientCredentialType="UserName"/>
      </security>
    </binding>
  </basicHttpBinding>
</bindings>
<behaviors>
  <serviceBehaviors>
    <behavior name="bsHttpBehavior">
      <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
      <serviceDebug includeExceptionDetailInFaults="false"/>
      <serviceCredentials>
        <userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="xxx.UserNamePassValidator, xxx"/>
      </serviceCredentials>
    </behavior>
  </serviceBehaviors>
</behaviors>
<services>
  <service behaviorConfiguration="bsHttpBehavior" name="xxx.MobilService">
    <endpoint address="" binding="basicHttpBinding" bindingConfiguration="basicHttp" contract="xxx.IMobilService"/>
    <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
    <host>
      <baseAddresses>
        <add baseAddress="http://localhost:4099/"/>
      </baseAddresses>
    </host>
  </service>
</services>

    

2 个答案:

答案 0 :(得分:0)

在我看来,首先,您应该通过SOAP-UI应用程序或类似的东西来检查服务。

答案 1 :(得分:0)

public static String WCFShow (String METHOD_NAME, int timeOut, List<KSoapParameters> parameters)  {

    SoapObject request = new SoapObject(Constant.NAMESPACE, METHOD_NAME);
    for (int i =0;i<parameters.size();i++){
        request.addProperty(parameters.get(i).getKey(),parameters.get(i).getValue());
    }
    SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
    envelope.dotNet = true;
    List<HeaderProperty> header = new ArrayList<HeaderProperty>();
    header.add(new HeaderProperty("Authorization","Basic "+org.kobjects.base64.Base64.encode("admin:adminpass".getBytes())));
    envelope.setOutputSoapObject(request);

    Element headers[] = new Element[1];
    headers[0]= new Element().createElement("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", "Security");
    headers[0].setAttribute(envelope.env, "mustUnderstand", "1");
    Element security=headers[0];

    Element token = new Element().createElement(security.getNamespace(), "UsernameToken");
    token.setAttribute("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd", "Id", "UsernameToken-2");

    Element username = new Element().createElement(security.getNamespace(), "Username");
    username.addChild(Node.TEXT, "admin");
    token.addChild(Node.ELEMENT,username);

    Element password = new Element().createElement(security.getNamespace(), "Password");
    password.setAttribute(null, "Type", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText");
    password.addChild(Node.TEXT, "adminpass");
    token.addChild(Node.ELEMENT,password);

    headers[0].addChild(Node.ELEMENT, token);

    envelope.headerOut = headers;

    HttpTransportSE aht = new HttpTransportSE(Constant.URL,timeOut);
    aht.debug = true;

    try {
        aht.call(Constant.SOAP_ACTION+METHOD_NAME, envelope, header);
        //Log.d("AAAAASSSSSSDDDDD", envelope.getResponse().toString());
//            Object result = envelope.getResponse();
        Object result = envelope.bodyIn;

        resultData = result.toString();
        //Log.d("ERDINC", resultData.toString());
    } catch (IOException e) {
        e.printStackTrace();
        resultData="ERROR"+e.toString();
    } catch (XmlPullParserException e) {
        e.printStackTrace();
        resultData="ERROR"+e.toString();
    }

    return resultData;
}

我添加并工作:)

password.setAttribute(null, "Type", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText");