WebService的几种验证方式

Posted ☆Keep★Moving☆

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了WebService的几种验证方式相关的知识,希望对你有一定的参考价值。

 

转 http://www.cnblogs.com/yoshiki1895/archive/2009/06/03/1495440.html

 

 

1.1      WebService设计

1.1.1   传输基本参数

1.1.2   传输数据集合

(1)     数组

(2)     DataSet

1.2      WebService异常处理

1.3      WebService性能

1.4      WebService认证

 请参考WebService认证学习报告

1.4.1   各种认证方式

1.4.1.1      Windows认证

(1)   配置IIS中WebService文件的权限为集成Windows认证

 

(2)   设置Web.Config

<authentication mode= "Windows">

</authentication>

 

 

1.4.2   跟踪用户访问

1.5      WebService调用

1.5.1   Windows认证

(1)   NT认证使用时,Credentials必须指定System.Net.CredentialCache.DefaultCredentials

当设置为default时,客户端根据服务端配置决定采用NTLM认证还是其他的安全认证

(2)   实例化WebService对象

(3)   添加WebService认证信息

(4)   调用WebService方法

            LocalTest.GIISService localTest = new LocalTest.GIISService();

            CredentialCache credentialCache = new CredentialCache();

            NetworkCredential credentials = new NetworkCredential("XuJian", "password", "Snda");

            credentialCache.Add(new Uri("http://localhost/GIIS/ GIISService.asmx"),

                                "Basic", credentials);

            localTest.Credentials = credentialCache;

            string tt = localTest.Hello("ssssssss");

1.6      GIIS中WebService认证实现

该部分为本次GIIS中实现的认证方式,考虑到相关配置、维护性,不涉及其他认证方式的处理

1.6.1   实现方式

 SOAP Header + DES加解密 + Windows认证

1.6.2   实现原理

(1)   SOAP Header

SOAP包括四个部分: SOAP封装(envelop),定义描述消息

SOAP编码规则

                                   SOAP RPC调用和应答协定

                                   SOAP绑定,底层协议交换信息

其中envelop由一个或多个Header和一个Body组成,Header元素的每一个子元素称为一个SOAP Header

(2)   DES对称加解密

通过Client端传输过来的已加密编码,在客户端进行解码分析,实现认证,认证的user信息来自于GIIS的系统登录用户列表

对编码和解码的字节类型存储在Web.Config文件中,要保持一致并对称,且字符长度需设为8位

 

(3)   集成Windows认证

作为域用户可以通过该方式来调用、处理WebService,但非域用户看通过我们自定义的SOAP Header方式来验证

1.6.3   实现步骤(SOAP)

(1)   设置.asmx文件的访问权限为“集成Windows认证”,不允许匿名访问

 

(2)   创建WebService认证类CredentialSoapHeader.cs,继承SoapHeader

*调用者的信息从系统维护的WscUser表中获取

namespace XXX.WebService

{

    public class CredentialSoapHeader : System.Web.Services.Protocols.SoapHeader

    {

        #region -- Private Attribute --

        private string m_UserID = string.Empty;

        private string m_Password = string.Empty;

        #endregion

 

        #region -- Private Attribute --

        /// <summary>

        /// user id

        /// </summary>

        public string UserID

        {

            get

            {

                return m_UserID;

            }

            set

            {

                m_UserID = value;

            }

        }

 

        /// <summary>

        /// user password

        /// </summary>

        public string PassWord

        {

            get

            {

                return m_Password;

            }

            set

            {

                m_Password = value;

            }

        }

        #endregion

 

        /// <summary>

        /// initial user id and papssword

        /// </summary>

        /// <param name="userID">user id</param>

        /// <param name="password">user password</param>

        public void Initial(string userID, string password)

        {

            UserID = userID;

            PassWord = password;

        }

 

        /// <summary>

        /// check user when use web service

        /// </summary>

        /// <param name="userID">user id</param>

        /// <param name="password">user password</param>

        /// <param name="message">return message</param>

        /// <returns></returns>

        public bool IsValid(string userID, string password, out string message)

        {

            message = "";

            try

            {

                string userName = Encrypt.DecryptClient(userID);

                string userPassword = Encrypt.DecryptClient(password);

                Entity.GiWscuser userAuthority = new Entity.GiWscuser();

                userAuthority.QueryMode = true;

                userAuthority.Active += true;

                userAuthority.Account += userName.Trim();

                userAuthority.Password += userPassword.Trim();

                DataTable dtblUser = userAuthority.Query(

                    new String[] {userAuthority.Account, userAuthority.Password }, false, -1).Tables[0];

                if (dtblUser.Rows.Count > 0)

                {

                    return true;

                }

                else

                {

                    message = "sorry, you have no access authority for current web service";

                    return false;

                }

            }

            catch(Exception ex)

            {

                message = "sorry, you have no access authority for current web service " + ex.Message;

                return false;

            }

        }

 

        /// <summary>

        /// check user authority

        /// </summary>

        /// <param name="message">message tip</param>

        /// <returns></returns>

        public bool IsValid(out string message)

        {

            return IsValid(m_UserID, m_Password, out message);

        }

    }

}

(3)   创建DES加解密类,实现明文编码与解码

     public class Encrypt

     {                 

         private static string ms_Key = System.Configuration.ConfigurationManager.AppSettings["EncryptKey"];

        private static string ms_IV = System.Configuration.ConfigurationManager.AppSettings["EncryptIV"];

 

         /// <summary>

         /// Encrypt a string

         /// </summary>

         /// <param name="ecryptString">string needs to be encrypted</param>

         /// <returns>the encrypted string</returns>

         public static string EncryptClient(string ecryptString)

         {

              if(ecryptString != "")

              {

                   DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();

                   cryptoProvider.Key = ASCIIEncoding.ASCII.GetBytes(ms_Key);

                   cryptoProvider.IV = ASCIIEncoding.ASCII.GetBytes(ms_IV);

                   MemoryStream memoryStream = new MemoryStream();

                   CryptoStream cryptoStream = new CryptoStream(memoryStream,

                       cryptoProvider.CreateEncryptor(), CryptoStreamMode.Write);

                   StreamWriter streamWriter = new StreamWriter(cryptoStream);

                   streamWriter.Write(ecryptString);

                   streamWriter.Flush();

                   cryptoStream.FlushFinalBlock();

                   memoryStream.Flush();

                   return Convert.ToBase64String(memoryStream.GetBuffer(),0,Int32.Parse(memoryStream.Length.ToString()));

              }

              else

              {

                   return "";

              }

         }

 

         /// <summary>

         /// Decrypt a string

         /// </summary>

         /// <param name="decryptString">string needs to be decrypted</param>

         /// <returns>the decrypted string</returns>

         public static string DecryptClient(string decryptString)

         {

              if(decryptString != "")

              {

                   DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();

                   cryptoProvider.Key = ASCIIEncoding.ASCII.GetBytes(ms_Key);

                   cryptoProvider.IV = ASCIIEncoding.ASCII.GetBytes(ms_IV);

                   Byte[] buffer = Convert.FromBase64String(decryptString);

                   MemoryStream memoryStream = new MemoryStream(buffer);

                   CryptoStream cryptoStream = new CryptoStream(memoryStream, cryptoProvider.CreateDecryptor(), CryptoStreamMode.Read);

                   StreamReader streamReader = new StreamReader(cryptoStream);

                   return streamReader.ReadToEnd();

              }

              else

              {

                   return "";

              }

         }

 

(4)   在CredentialSoapHeader类中实现用户认证信息的解码与合法性检查,给出异常时的提示信息

见CredentialSoapHeade的代码

(5)   在目标Service类中实例化CredentialSoapHeader对象,并指定该对象为WebService方法的修饰

Namespace WebServiceAuthority

{

    [WebService(Namespace = "http://tempuri.org/")]

    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

    public class GIISService : System.Web.Services.WebService

    {

        public CredentialSoapHeader myHeader = new CredentialSoapHeader();

        /// <summary>

        /// get web service information by authority user

        /// </summary>

        /// <param name="contents">customize content</param>

        /// <returns></returns>

        [SoapHeader("myHeader")]

        [WebMethod(Description = "authority set for Web Service", EnableSession =true)]

        public string HelloWorld(string contents)

        {

            string message = "";

            if (!myHeader.IsValid(out message))

                return message;

            return "Hello World:" + contents;

        }

    }

}

 

1.6.4   Client端调用方法(SOAP)

(1)   添加WebService引用

 

URL地址为对应的GIIS WebService地址,引用的别名自定义

(2)   实例化一个WebService的类对象

LocalService.GIISService localTest = new LocalService.GIISService();

(3)   设置Credentials方式

localTest.Credentials = System.Net.CredentialCache.DefaultCredentials;

(4)   传递编码后的密文

(5)   调用WebService提供的方法

(6)   实现代码如下:

            LocalService.GIISService localTest = new LocalService.GIISService();

            localTest.Credentials = System.Net.CredentialCache.DefaultCredentials;//default credetials

            LocalService.CredentialSoapHeader header = new LocalService.CredentialSoapHeader();//Create SOAP header

            header.UserID = userName;//Set SOAP header user name information

            header.PassWord = userPassword;//Set SOAP header user password information

            localTest.CredentialSoapHeaderValue = header;

            this.Label1.Text = localTest.HelloWorld("ss");

至此已实现GIIS中的WebService验证,如单独采用Windows认证请参见下面的说明

以上是关于WebService的几种验证方式的主要内容,如果未能解决你的问题,请参考以下文章

webservice访问的几种方式

动态调用WebService接口的几种方式

WebService请求的几种方式

java Webservice都有哪几种方式啊,哪种方式比较好啊

WebService—实现接口发布和客户端调用的几种方式

开发Web Service的几种方式