Asp.Net安全验证小结
1,基于windows的安全验证
web.config文件:
<configuration>
<system.web>
<authentication mode="Windows" />
<identity impersonate="true" />
<authorization>
<allow roles="BUILTIN\groupname" users="computername\UserName,computername\UserName" />
<deny users="*" />
</authorization>
</system.web>
</configuration>
在.aspx文件中无需任何代码就可以实现验证,但可以在.aspx文件获取登陆用户的信息
需导入命名空间:System.Security.Principal
if(User.Identity.IsAuthenticated)//判断用户是否验证,似乎可有可无
{
WindowsIdentity objWinIdentity=WindowsIdentity.GetCurrent();
lblHelloMsg.Text="the name:"+objWinIdentity.Name+"<br>Type:"+ objWinIdentity.AuthenticationType+"IsInRole:"+User.IsInRole("computername\\groupname");
}
2,基于web.config forms验证
web.config文件:
<configuration>
<system.web>
<authentication mode="Forms">
<forms name="MyApp" path="/" loginUrl="login.aspx"
protection="All" timeout="30">
<credentials passwordFormat="Clear">
<user name="kwk" password="test" />
<user name="ljx" password="test" />
</credentials>
</forms>
</authentication>
<authorization>
<allow users="kwk,ljx" />
<deny users="?" />
</authorization>
</system.web>
</configuration>
login.aspx文件:需要提供两个文本框用于填写用户和密码(txtUsr,txtPwd),一个单选框判断是否永久保存
还需要一个按钮控件则响应该button的代码如下:
void DoLogin(Object sender, EventArgs e)
{
if(FormsAuthentication.Authenticate(txtUsr.Value,txtPwd.Value))
{
FormsAuthentication.RedirectFromLoginPage(txtUsr.Value,chkPersist.Checked);
}
else
//为代码完整性而设置,可以不写
{
Response.Write("authentication fails");
}
}
然后在别的页面可以获得登陆用户的值:
if(User.Identity.IsAuthenticated)//可以不需要判断
{
Response.Write("your name:"+User.Identity.Name);
Response.Write("验证类型:"+User.Identity.AuthenticationType);//forms,windows等
}
3,基于自定义forms验证
web.config文件(基本上不需要什么设置):
<system.web>
<authentication mode="Forms">
<forms name="MyApp" path="/" loginUrl="custom-login.aspx"
protection="All" timeout="30" >
</forms>
</authentication>
<authorization>
<deny users="?" />
</authorization>
</system.web>
custom-login.aspx文件,基本原理还是跟2中说的一样,如:
if (blnIsAuthenticated) //注意这个blnIsAuthenticated是一个自己定义的变量
//当我们把用户输入的信息和数据库(或xml)的信息比对,存在则把该变量设为true,反之false
//这是跟2不一样的地方
{
FormsAuthentication.RedirectFromLoginPage(txtUsr.Value, chkPersist.Checked);
//txtUsr和chkPersist分别为textbox,checkbox控件
}
else
{
//验证失败提示信息
}
剩下的如在其他页面获得用户信息,如2一样
4,退出登陆
响应退出登陆按钮的代码:
FormsAuthentication.SignOut();
Response.Clear();
Response.Redirect(Request.UrlReferrer.ToString());//重定向到前一个页面
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?