ASP 封装基本身份认证( HTTP Basic Authenticate)辅助类
最近修改一个古老的asp程序,需要为单独几个页面进行基本身份认证。由于IIS自带的设置基本身份认证是针对文件夹的,而这几个页面又不方便挪动位置,幸好在网上找到一个asp实现WWW-Authenticate basic认证示例,简单修改封装成了一个辅助类,基本满足需要。
<% Class BasicAuthHelper Public Sub Unauth() 'realm不要设置为中文,会乱码 Call Response.AddHeader("WWW-Authenticate", "Basic realm=""Please input username and password""") Response.Status = "401 Unauthorized" Call Response.End() End Sub Public Function Authenticate(byval uid, byval pwd) Dim strAuth:strAuth = Request.ServerVariables("HTTP_AUTHORIZATION") If IsNull(strAuth)=False and IsEmpty(strAuth)=False and strAuth <> "" Then Dim aParts, aCredentials, strType, strBase64, strPlain, strUser, strPassword aParts = Split(strAuth, " ") If aParts(0) = "Basic" Then dim base64 : set base64 = new Base64Helper strPlain = base64.Decode(aParts(1)) aCredentials = Split(strPlain, ":") 'response.write "strAuth=" & strAuth
'response.write "aParts(1)=" & aParts(1)
'response.write "strPlain=" & strPlain
'response.write "UBound(aCredentials)=" & UBound(aCredentials)
if UBound(aCredentials) = 1 then strUser = aCredentials(0) strPassword= aCredentials(1) 'response.write "strUser=" & strUser & ", strPassword=" & strPassword
'用户名和密码正确则返回True,这里也可以改为数据库验证之类的 if strUser = uid and strPassword = pwd then Authenticate = True Exit Function End if end if End If End if '不正确 Authenticate=False End Function End Class dim basicAuth: set basicAuth=new BasicAuthHelper if basicAuth.Authenticate("admin","pass") then Response.write "Authenticate OK" else basicAuth.Unauth() end if %>
PS: 虽然近日微软开始放风打算要彻底抛弃 Visual Basic了,但是从IIS一直支持 asp 这一点上看来,还是很厚道滴