ASP 封装基本身份认证( HTTP Basic Authenticate)辅助类

最近修改一个古老的asp程序,需要为单独几个页面进行基本身份认证。由于IIS自带的设置基本身份认证是针对文件夹的,而这几个页面又不方便挪动位置,幸好在网上找到一个asp实现WWW-Authenticate basic认证示例,简单修改封装成了一个辅助类,基本满足需要。

复制代码
<!--#include file="base64Helper.asp" -->
<%
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 "<p>strAuth=" & strAuth
                'response.write "<p>aParts(1)=" & aParts(1)
                'response.write "<p>strPlain=" & strPlain
                'response.write "<p>UBound(aCredentials)=" & UBound(aCredentials)
                
                
                if UBound(aCredentials) = 1 then
                    strUser = aCredentials(0)
                    strPassword= aCredentials(1)

                    'response.write "<p>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 这一点上看来,还是很厚道滴

 

posted @   树欲静·而风不止  阅读(355)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示