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

2025-05-29 0 60

本文实例讲述了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文件如下:

?

1

2

3

4

5

6

7

8

9

10

11

12
<?xml version="1.0" encoding="utf-8"?>

<configuration>

<system.web>

<compilation debug="false" />

<authentication mode="Forms">

<forms name="MyService" loginUrl="Login.asmx"></forms>

</authentication>

<authorization >

<deny users="?"/>

</authorization>

</system.web>

</configuration>

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

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

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14
[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。

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16
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,就这么简单!

希望本文所述对大家的C#程序设计有所帮助。

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 ASP.NET实现基于Forms认证的WebService应用实例 https://www.kuaiidc.com/101417.html

相关文章

发表评论
暂无评论