日期:2014-05-18  浏览次数:20437 次

如何实现基于角色的验证?
以下是一些有关的文件内容,我想在Albums.aspx页面中根据用户角色不同给予不同提示信息,但Joan属于Supervisor角色,但joan用户进入后显示的信息是没有Supervisor权限,各位帮忙看看,谢谢!
Web.config的内容:
<authentication mode="Forms" >
  <forms loginUrl="Default.aspx" defaultUrl="Albums.aspx" name=".UserCookie" protection="Validation" timeout="200">
  <credentials passwordFormat="Clear">
  <user name="joan" password="joan"/>
  <user name="mike" password="mike"/>
  </credentials>
  </forms>
  </authentication>

 <location path="Albums.aspx">
  <system.web>
  <authorization>
  <deny users="?"/>
  </authorization>
  </system.web>
  </location>

Users.xml中的内容:
<?xml version="1.0" encoding="utf-8" ?>
<roles>
  <user name="mike" roles="Sales"/>
  <user name="joan" roles="Supervisor,Sales"/>
</roles>

Global.asax中的内容:
void Application_AuthenticateRequest(object sender,EventArgs e)
  {
  XmlDocument xd;
  XmlNode xn;
  string userName;
  string strXPath;
  string[] arrRole;
  if(Context.Request.IsAuthenticated)
  {
  xd = GetUsers();
  userName = Context.User.Identity.Name;
  strXPath = string.Format("user[@name='{0}']",userName);
  xn = xd.SelectSingleNode(strXPath);
  if(xn!=null)
  {
  arrRole=xn.Attributes["roles"].Value.Split(',');
  Context.User = new GenericPrincipal(Context.User.Identity,arrRole);
  }
  }
   
  }

  public XmlDocument GetUsers()
  {
  XmlDocument xd;
  xd=(XmlDocument)Context.Cache["Users"]; 
  if(xd==null)
  {
  string xmlPath = Server.MapPath("Users.xml");
  xd = new XmlDocument();
  xd.Load(xmlPath);
  Context.Cache.Insert("Users",xd,new CacheDependency(xmlPath));
  }
  return xd;
  }

Albums.aspx中的内容:
  protected void Page_Load(object sender, EventArgs e)
  {
  Response.Write("<h3>Welcome " + User.Identity.Name + " to My HomePage!</h3>");
  if (User.IsInRole("Supervisor"))
  {
  Response.Write("<hr/>You have supervisor permission!");
  }
  else
  {
  Response.Write("<hr/>You don't have supervisor permission!");
  }
  }



------解决方案--------------------
验证票一共有大概7个参数,其中有个参数是userdata,在这个理可以构造角色信息