Fork me on GitHub

HTTP Basic Authentication for RESTFul Service

面对用户认证的问题。最常见的实现方式一般是这样的:用户提交一个含有用户名和密码的表单,服务端脚本验证其合法性,如果通过验证,则在Session里标识一下,如此一来,在同一个Session周期里,用户就维持了自己的认证状态。基于Session的认证最大的问题在于它不符合REST风格,更直接一点说,它破坏了HTTP的无状态特性,从而对可扩展性造成障碍。
RFC2617里规定的两种标准的认证方式(Baisc,Digest),和Session方式最根本的不同是,它们是符合HTTP无状态特性的,所以相对而言更值得推荐。

什么是HTTP Basic Authentication?直接看http://en.wikipedia.org/wiki/Basic_authentication_scheme吧。

在你访问一个需要HTTP Basic Authentication的URL的时候,如果你没有提供用户名和密码,服务器就会返回401,如果你直接在浏览器中打开,浏览器会提示你输入用户名和密码(google浏览器不会).

要在发送请求的时候添加HTTP Basic Authentication认证信息到请求中,有两种方法:

  • 一是在请求头中添加Authorization:
    Authorization: "Basic 用户名和密码的base64加密字符串"
  • 二是在url中添加用户名和密码:

WCF Data Services团队最近发表了一系列关于OData服务和客户端上可用验证机制的文章。具体参看http://www.infoq.com/cn/news/2010/07/odata-authentication-series,其中也有介绍到HTTP Basic Authentication :

Custom Basic Authentication(自定义基本验证)——涉及在基础结构级别(如IIS)上进行的基本质询响应(challenge-response)验证的场景。假如简单的用户名/密码不能满足要求,还要支持用户/密码信息存储在数据库中的情况。

对于IIS 7来说,Codeplex上有个项目可以解决这个问题:http://custombasicauth.codeplex.com

customBasicAuth的安装方法:

1、已管理员身份打开命令行

rem ----------- !!! RUN AS ADMINISTRATOR !!!
rem ---
2、将程序集注册到GAC

----------- 1 GAC DLLs -----------------

rem HTTP module
gacutil -if LeastPrivilege.CustomBasicAuthenticationModule.dll

rem Server configuration module
gacutil -if LeastPrivilege.CustomBasicAuthentication.Management.dll

rem Client UI module
gacutil -if LeastPrivilege.CustomBasicAuthentication.Management.Client.dll

3、注册CustomBasicAuthentication_schema

rem ----------- 2 Register Schema -----------------
iisschema.exe /install CustomBasicAuthentication_schema.xml

4、注册管理端

rem----------- 2 Register Management  -----------------
IisRegMgmt CustomBasicAuth LeastPrivilege.CustomBasicAuthentication.Management.CustomBasicAuthenticationModuleProvider LeastPrivilege.CustomBasicAuthentication.Management.dll

5、在具体的Web应用程序中设置,主要参考下面的文章:

http://www.leastprivilege.com/HTTPBasicAuthenticationAgainstNonWindowsAccountsInIISASPNETPart3AddingWCFSupport.aspx

相关文章:

Custom Security OData Service – Wcf Data Services

http://franssenden.wordpress.com/2010/06/14/custom-security-odata-service-wcf-data-services/

posted @ 2010-08-08 10:34  张善友  阅读(5307)  评论(0编辑  收藏  举报