当前位置: 移动技术网 > IT编程>开发语言>.net > ASP.NET Forms身份认证

ASP.NET Forms身份认证

2017年12月08日  | 移动技术网IT编程  | 我要评论

撸儿所最新更新的电影 一一影院,青羽软剑,竞选ppt

asp.net程序开发,用户根据角色访问对应页面以及功能。

项目结构如下图:

根目录 web.config 代码:

<?xml version="1.0" encoding="utf-8"?>
<!--
 有关如何配置 asp.net 应用程序的详细消息,请访问
 http://go.microsoft.com/fwlink/?linkid=169433
 -->
<configuration>
  <system.web>
    <compilation debug="true" targetframework="4.0" />
    <authentication mode="forms">
     <forms loginurl="login.aspx"></forms>
    </authentication>
    <!--<authorization>
     <allow users="*"></allow>
    </authorization>-->
  </system.web>
</configuration>

admin文件夹中 web.config 代码:

<?xml version="1.0"?>
<configuration>
 <system.web>
 <authorization>
 <allow roles="admin" />
 <deny users="*"/>
 </authorization>
 </system.web>
</configuration>

teacher文件夹中 web.config 代码:

<?xml version="1.0"?>
<configuration>
 <system.web>
 <authorization>
 <allow roles="teacher" />
 <deny users="*"/>
 </authorization>
 </system.web>
</configuration>

student文件夹中 web.config 代码:

<?xml version="1.0"?>
<configuration>
 <system.web>
 <authorization>
 <allow roles="student" />
 <deny users="*"/>
 </authorization>
 </system.web>
</configuration>

login.aspx中登录成功后设置cookie,设置cookie代码:

protected void setlogincookie(string username, string roles)
{
system.web.security.formsauthentication.setauthcookie(username, false);
 system.web.security.formsauthenticationticket ticket = new formsauthenticationticket(1, username, datetime.now, datetime.now.adddays(1), false, roles, "/");
 string hashticket = formsauthentication.encrypt(ticket);
 httpcookie usercookie = new httpcookie(formsauthentication.formscookiename, hashticket);
 httpcontext.current.response.setcookie(usercookie);
}

global.asax 中进行身份验证:

protected void application_authenticaterequest(object sender, eventargs e)
{
 httpapplication app = (httpapplication)sender;
 httpcontext ctx = app.context; //获取本次http请求的httpcontext对象 
 if (ctx.user != null)
 {
 if (ctx.request.isauthenticated == true) //验证过的一般用户才能进行角色验证 
 {
 system.web.security.formsidentity fi = (system.web.security.formsidentity)ctx.user.identity;
 system.web.security.formsauthenticationticket ticket = fi.ticket; //取得身份验证票 
 string userdata = ticket.userdata;//从userdata中恢复role信息
 string[] roles = userdata.split(','); //将角色数据转成字符串数组,得到相关的角色信息 
 ctx.user = new system.security.principal.genericprincipal(fi, roles); //这样当前用户就拥有角色信息了
 }
 }
}

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持移动技术网!

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网