问题
I'm building a Xamarin app that requires a WCF service, the service will be protected using SSL (self signed cert for development purposes) and Username Authentication.
The service works and when creating a service reference
in a WinForms project it all works fine like so:
CategoryServiceClient csc = new CategoryServiceClient();
csc.ClientCredentials.UserName.UserName = "shaun";
csc.ClientCredentials.UserName.Password = "TEST";
System.Net.ServicePointManager.ServerCertificateValidationCallback +=
(se, cert, chain, sslerror) => { return true; };
var a = csc.TestService();
In Xamarin I can only add a Web Reference
and not a Service Reference
so I need to change my code to this:
private void TestConnection() {
CatServiceRef.CategoryService cs = new CatServiceRef.CategoryService();
cs.Credentials = new Creds();
System.Net.ServicePointManager.ServerCertificateValidationCallback +=
(se, cert, chain, sslerror) => { return true; };
try {
string s = cs.TestService();
}
catch (Exception ex) {
throw;
}
}
public class Creds : ICredentials {
public NetworkCredential GetCredential(Uri uri, string authType) {
return new NetworkCredential("Shaun", "TEST");
}
}
But an exception is thrown:
System.Web.Services.Protocols.SoapException: The security context token is expired or is not valid. The message was not processed.
How do I solve this?
WCF Service auth code:
public override void Validate(string userName, string password) {
if (null == userName || null == password) {
throw new ArgumentNullException();
}
if (!(userName.ToLower() == "shaun" && password == "TEST")) {
throw new FaultException("Incorrect Username or Password");
}
}
来源:https://stackoverflow.com/questions/19936247/xamarin-how-to-add-service-reference-to-ssl-username-authentication-wcf-service