I am building an application and integrating it with active directory.
So I authenticate my app user to active directory users, after that I store some of user's data like : user group and user profile
to Generic principal and user identity to Generic identity.
My problem is I can't get user profile data from generic principal when I want to use it.
Can someone show me how to do that?
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;
Note : Code above is in global asax file, and I want to use user profile data which I stored in generic principal in another file named default.aspx
.
So first off you shouldn't be doing this:
GenericPrincipal principal = new GenericPrincipal(id, userProfileData);
//^^ this is wrong!!
The second argument to the constructor is for Roles. See the docs.
If you want to store data into the generic principal then what you should do is
Create a class out of GenericIdentity
:
class MyCustomIdentity : GenericIdentity
{
public string[] UserData { get; set;}
public MyCustomIdentity(string a, string b) : base(a,b)
{
}
}
Create it like this:
MyCustomIdentity =
new MyCustomIdentity(authTicket.Name,"LdapAuthentication");
//fill the roles correctly.
GenericPrincipal principal = new GenericPrincipal(id, new string[] {});
Get it in the page like this:
The Page class has a User property.
So for example in Page load you could do this:
protected void Page_Load(object sender, EventArgs e) {
MyCustomIdentity id = (MyCustomIdentity)this.User.Identity
var iWantUserData = id.UserData;
}
You can also use the following code:
FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity;
string userData = id.Ticket.UserData
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With