[C#].net webservice实现调用身份认证

WebService发布之后,任何用户都可以对其进行调用,为了防止一些接口被匿名用户访问,可以对.net webservice实现调用认证,把要认证的信息填入SoapHeader中,在调用Api时一并发给服务端,服务端取出认证信息进行验证,如果通过,则继续执行,如果不通过,则返回错误信息,这样就达到了验证调用者身份的效果,下面来说说具体做法:

假设现在我们有一个WebService,里面有一个HelloWorld方法,

[WebService(Namespace = "http://tempuri.org")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
public class HwWebService : System.Web.Services.WebService 
{
	[WebMethod]
	public string HelloWorld()
	{
		return "Hello World";
	}
}

首先自定义一个消息类,用于存放验证信息,继承自SoapHeader。

public class AuthorizeHeader : SoapHeader
{
	public string User
	{ get; set; }

	public string Password
	{ get; set; }
}

接着我们在WebService代码里加入一个AuthorizeHeader实例,用于接收客户端传递过来的认证信息。注意一定要是public的,不然外部访问不到会报错。

public AuthorizeHeader authHeader = null;

然后在刚才的HelloWorld方法上加入一个新的Atrribute

[SoapHeader("authHeader")]

我们看一下SoapHeader构造方法的说明,有这么一段:

// Summary:
//     Initializes a new instance of the System.Web.Services.Protocols.SoapHeaderAttribute
//     class, setting the member of the XML Web service class representing the SOAP
//     header contents.
//
// Parameters:
//   memberName:
//     The member of the XML Web service class representing the SOAP header contents.
//     The System.Web.Services.Protocols.SoapHeaderAttribute.MemberName property
//     will be set to the value of this parameter.
public SoapHeaderAttribute(string memberName);

可以看到叫memberName的属性将会被赋值为SOAP header的内容,这样我们上面[SoapHeader(“authHeader”)]里的authHeader就可以拿到SoapHeader的值了。

博主为你专属推荐


拿到验证内容,现在我们来加一个验证方法:

private bool ValidateUser(string user, string pw)
{
	if(user == "Hello" && pw == "World")
		return true;
	return false;
}

改造一下HelloWorld方法:

[WebMethod]
[SoapHeader("authHeader")]
public string HelloWorld()
{
	if(authHeader == null || !ValidateUser(authHeader.User, authHeader.Password))
		return "You Don't have permission to access this API.";
	
	return "Hello World!";
}

接下来用客户端测试一下:

static void Main(string[] args)
{
	HwWebservice hw = new HwWebservice();
	Console.WriteLine(hw.HelloWorld());
	hw.AuthorizeHeaderValue = new AuthorizeHeader();
	hw.AuthorizeHeaderValue.User = "Hello";
	Console.WriteLine(hw.HelloWorld());
	hw.AuthorizeHeaderValue.Password = "World";
	Console.WriteLine(hw.HelloWorld());
}

运行结果:
authSoap

完整代码地址:
http://pan.baidu.com/s/1eQ9Ujrs

打赏

博主开通了微信公众号,欢迎关注啦

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.