WebService(asp.net的asmx)调用安全认证
1、Soap头:
(1)、服务端:
/// <summary>
/// 安全头
/// </summary>
public class WsSecurityHeader : SoapHeader
{
public WsSecurityHeader()
{
}
public WsSecurityHeader(string key):this()
{
this.Key = key;
}
public string Key { get; set; }
}
public class WebService1 : System.Web.Services.WebService
{
public WsSecurityHeader CallKey = new WsSecurityHeader();
[SoapHeader("CallKey")]
public string HelloWorld()
{
//安全检查
//安全检查
if (String.Compare(CallKey.Key, "0", StringComparison.CurrentCultureIgnoreCase) != 0)
{
throw new ApplicationException("未通过验证");
}
//实际服务方法
Random r = new Random();
return "Hello "
+ (char) (r.Next((int) 'A', (int) 'Z' + 1))
+ (char) (r.Next((int) 'a', (int) 'z' + 1))
+ "!";
}
}
(2)、调用客户端:
public static WsCallSecurityTest.WebService1 Ws1
{
get
{
if (_ws1 == null)
{
_ws1 = new WebService1();
//Soap头
WsCallSecurityTest.WsSecurityHeader header = new WsSecurityHeader();
header.Key = "0";
_ws1.WsSecurityHeaderValue = header;
}
return _ws1;
}
}
private static WsCallSecurityTest.WebService1 _ws1;
//调用时
string s = Ws1.HelloWorld();
2、IIS取消匿名用户访问,并集成Windows身份验证
(1)、服务端
例如在IIS6的“目录安全性”-》“身份验证和访问控制”-》编辑-》“启用匿名访问“取消勾选,”集成Windows身份验证“勾选。
代码无变化
(2)、调用客户端(大部分同上,注意红色部分):
public static WsCallSecurityTest.WebService1 Ws1
{
get
{
if (_ws1 == null)
{
_ws1 = new WebService1();
//若无则会报401错:“请求因 HTTP 状态 401 失败: Unauthorized。”
_ws1.Credentials = new NetworkCredential("WsCallUser", "0"); //服务器用户名和密码
//Soap头
WsCallSecurityTest.WsSecurityHeader header = new WsSecurityHeader();
header.Key = "0";
_ws1.WsSecurityHeaderValue = header;
}
return _ws1;
}
}
private static WsCallSecurityTest.WebService1 _ws1;