locked
Custom principal not casting back RRS feed

  • Question

  • We created a custom principal a while back to swap out the Windows security information NTID with an employee ID we read from a DB. The basic code was like this (name is the employee ID we pass in):

        public class customPrincipal : IPrincipal
        {
            public customPrincipal(string name)
            {
                System.Security.Principal.GenericIdentity oUser = new System.Security.Principal.GenericIdentity(name);
                _Identity = oUser;
            }
         }

    We would load the information in the global.asax something like this (I left out the code where we get the employee ID string):

    private void Application_AuthenticateRequest(object sender, System.EventArgs e)
    {
        //create new custom principal and update to user object
        customPrincipal cp = new customPrincipal(s_eid);
        HttpContext.Current.User = cp;
        //create auth cookie
        HttpCookie httpCook = new HttpCookie(sAppCookieName);
        httpCook = new HttpCookie(sAppCookieName, s_eid);
        HttpContext.Current.Response.Cookies.Add(httpCook);

    I was going to enhance this a bit and add to the custom principal the user name (and maybe later the email address). So I added a property for employee name and updated the constructor and changed the call in global.asax

    customPrincipal cp = new customPrincipal(s_eid, emp.EmpName);

    But when I try to use this information I get an error on the casting Unable to cast object of type 'System.Web.Security.RolePrincipal' to type 'OrgMonitorWeb.customPrincipal'.

        public class HomeController : Controller
        {
            public ActionResult CurrentUserName()
            {
                var cp = (customPrincipal)User;
                return PartialView(cp.EmpName);
            }
    I'm also trying to convert to C# and use MVC for the first time so it has been slow going but from the other postings I've read I think this should be correct. Am I missing something obvious?
    • Moved by Andreas Johansson Saturday, July 7, 2012 8:02 PM ASp.NET (From:.NET Base Class Library)
    Saturday, July 7, 2012 7:31 PM

Answers