WebService基于SoapHeader实现安全认证

来源:互联网 发布:沟通误区 知乎 编辑:程序博客网 时间:2024/05/22 11:57

本文仅提供通过设置SoapHeader来控制非法用户对WebService的调用.

 

SoapHeader使用步骤

1、自定义实现System.Web.WebServices.SoapHeader 的类。

using System.Web.Services.Protocols;

namespace SoapHeader
{
    public class AuthorizationInfo:SoapHeader
    {
        public string UserName;
        public string PassWord;
    }
}

 

2、在WebServices中创建拥有public访问权限的自定义SoapHeader字段。

   public AuthorizationInfo authinfo;

 

3、在需要使用SoapHeader的WebMethod上加上SoapHeaderAttribute 访问特性,SoapHeaderAttribute 构造必要指定memberName 参数,就是第二步定义的字段名。

        [WebMethod]
        [SoapHeader("authinfo")]
        public string GetCourse()

 

4、生成器会自动为客户端生成同名的自定义 SoapHeader 类型,只不过比起我们在 WebService 端创建的要复杂一些。同时还会为代理类型添加一个 soapheaderValue 属性。 

 

代码如下:

1、Soap类

using System.Web.Services.Protocols;

namespace SoapHead
{
    public class AuthorizationInfo:SoapHeader
    {
        public string UserName;
        public string PassWord;
    }
}

2、WebService

using System.Web.Services;
using System.Web.Services.Protocols;

namespace SoapHead
{
    /// <summary>
    /// Service1 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [ToolboxItem(false)]
    public class CourseService : System.Web.Services.WebService
    {
        public AuthorizationInfo authinfo;
        [WebMethod]
        [SoapHeader("authinfo")]
        public string GetCourse()
        {
            if (authinfo.UserName == "xiaoyoujun" && authinfo.PassWord == "123456")
            {
                return "WebService调用成功!";
            }
            else
            {
                return "WebService调用失败!";
            }
        }
    }
}

 

3、客服端

 protected void btnTest_Click(object sender, EventArgs e)
        {
            CourseService.AuthorizationInfo author = new           WebApplicationTest.CourseService.AuthorizationInfo();
            author.UserName = "xiaoyoujun";
            author.PassWord = "4";
            CourseService.CourseService cs = new WebApplicationTest.CourseService.CourseService();
            cs.AuthorizationInfoValue = author;
            Response.Write(cs.GetCourse());
        }


原创粉丝点击