Xamarin How to add service reference to SSL username authentication WCF service?

心不动则不痛 提交于 2020-01-17 04:42:46

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!