5

我正在构建一个应用程序并将其与活动目录集成。

因此,我将我的应用程序用户身份验证给活动目录用户,之后我将一些用户的数据存储为:user group and user profile到通用主体和用户身份到通用身份。

我的问题是当我想使用它时,我无法从通用主体获取用户配置文件数据。

有人可以告诉我怎么做吗?

 string cookieName = FormsAuthentication.FormsCookieName;
 HttpCookie authCookie = Context.Request.Cookies[cookieName];

 if (authCookie == null)
 {
       //There is no authentication cookie.
       return;
 }

 FormsAuthenticationTicket authTicket = null;

 try
 {
       authTicket = FormsAuthentication.Decrypt(authCookie.Value);
 }
 catch (Exception ex)
 {
      //Write the exception to the Event Log.
       return;
 }

 if (authTicket == null)
 {
      //Cookie failed to decrypt.
      return;
 }

 String data = authTicket.UserData.Substring(0, authTicket.UserData.Length -1);
 string[] userProfileData =   data.Split(new char[] { '|' });
 //Create an Identity.
 GenericIdentity id = 
                  new GenericIdentity(authTicket.Name, "LdapAuthentication");
 //This principal flows throughout the request.
 GenericPrincipal principal = new GenericPrincipal(id, userProfileData);
 Context.User = principal;

注意:上面的代码在全局 asax 文件中,我想使用我存储在另一个名为default.aspx.

4

2 回答 2

10

所以首先你不应该这样做:

GenericPrincipal principal = new GenericPrincipal(id, userProfileData);
                                                     //^^ this is wrong!!

构造函数的第二个参数是Roles。请参阅文档


如果您想将数据存储到通用主体中,那么您应该做的是

  1. 创建一个类GenericIdentity

    class MyCustomIdentity : GenericIdentity
    {
      public string[] UserData { get; set;}
      public MyCustomIdentity(string a, string b) : base(a,b)
      {
      }
    }
    
  2. 像这样创建它:

    MyCustomIdentity = 
               new MyCustomIdentity(authTicket.Name,"LdapAuthentication");
                                                      //fill the roles correctly.
    GenericPrincipal principal = new GenericPrincipal(id, new string[] {});
    
  3. 像这样在页面中获取它:

    Page类有一个User属性

    因此,例如在页面加载中,您可以这样做:

     protected void Page_Load(object sender, EventArgs e) {
      MyCustomIdentity id =  (MyCustomIdentity)this.User.Identity
      var iWantUserData = id.UserData;
     }
    
于 2013-04-24T05:03:43.217 回答
2

您还可以使用以下代码:

FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity;
string userData = id.Ticket.UserData
于 2014-08-12T13:26:35.317 回答