ASP.NET实现基于Forms认证的WebService应用实例

在安全性要求不是很高的ASP.Net程序中,基于Forms的身份验证是经常使用的一种方式,而如果需要对WebService进行身份验证,最常用的可能是基于Soap 标头的自定义身份验证方式。如果对两者做一下比较的话,显然,基于Forms的验证方式更加方便易用,能否将Forms验证方式应用到WebService中去呢?

从理论上讲,使用基于Forms的方式对WebService进行身份验证是可行的,但是使用过程中会存在以下两个问题:

1.基于Forms的验证方式同时也是基于Cookie的验证方式,在使用浏览器时,这个问题是不需要我们考虑的。但对于使用WebService的应用程序来说,默认是不能保存Cookie的,需要我们自己去做这个工作。

2.WebService既然是一个A2A(Application To Application)应用程序,使用Web表单进行身份验证显然不太合适,而且,这将不可避免的造成人机交互,使WebService的应用大打折扣。

接下来,我们就分步解决这两个问题:

1.Cookie的保存问题

WebService的客户端代理类有一个属性CookieContainer可用于设置或获取Cookie集合,保存Cookie的任务就交给他了:

System.Net.CookieContainer cookieContainer = new System.Net.CookieContainer();
MyService.WebService service = new App.MyService.WebService();
service.CookieContainer = cookieContainer;

2.我们不想使用Web表单进行身份验证,幸运的是,ASP.Net表单验证中的表单页(即Web.config文件中 forms 元素内的loginUrl)同样可以指定为WebService文件。
我们创建一个专门用作身份验证的Web服务,暂且命名为Login.asmx,然后让 loginUrl 等于 “Login.asmx”,当然,还需要在Web.config文件中的 authorization 节中禁止匿名访问(否则我们可就白忙活了),完成配置后的Web.config文件如下:

<?xml version="1.0" encoding="utf-8"?> <configuration> <system.web> <compilation debug="false" /> <authentication mode="Forms"> <forms loginUrl="Login.asmx"></forms> </authentication> <authorization > <deny users="?"/> </authorization> </system.web> </configuration>

其实我们并不想在未通过身份验证时让浏览器转向到Login.asmx,对于使用WebService的客户程序来说,真正的实惠在于:可以匿名访问Login.asmx中的方法(当然我们也可以把Login.asmx放在单独的目录中,然后允许对该目录的匿名访问来达个这个目的,但我觉得还是用loginUrl更优雅一些)。

接下来,我们为Login.asmx添加用于身份验证的WebMethod:

[WebMethod] public bool Check(string userName,string password) { if(userName == "aaaaaa" && password == "123456") //添加验证逻辑 { System.Web.Security.FormsAuthentication.SetAuthCookie(userName, false); return true; } else { return false; } }

最后一步工作就是:让客户程序中的WebService实例与Login实例共享CookieContainer。

class Sample { System.Net.CookieContainer cookieContainer = new System.Net.CookieContainer(); public void Login() { MyServiceLogin.Login login = new App.MyServiceLogin.Login(); login.CookieContainer = cookieContainer; login.Check("aaaaaa", "123456"); } public void ShowHelloWorld() { MyService.WebService service = new App.MyService.WebService(); service.CookieContainer = cookieContainer; Console.WriteLine(service.HelloWorld()); } }

Login()以后再ShowHelloWorld(),你是否看到了我们熟悉的“Hello World”?Ok,就这么简单!

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wjzyfw.html