Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.net: Replace GenericPrincipal

I was wondering what the best way is to replace the genericPrincipal with my own CustomGenericPrincipal.

At the moment I have something like this but I aint sure if it's correct.

protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
    HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
    if (authCookie != null)
    {
        FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
        var identity = new CustomIdentity(authTicket);
        var principal = new CustomPrincipal(identity);

        Context.User = principal;
    }
    else
    {
        //Todo: check if this is correct
        var genericIdentity = new CustomGenericIdentity();
        Context.User = new CustomPrincipal(genericIdentity);
    }
}

I need to replace it because I need a Principal that implements my ICustomPrincipal interface because I am doing the following with Ninject:

Bind<ICustomPrincipal>().ToMethod(x => (ICustomPrincipal)HttpContext.Current.User)
                        .InRequestScope();

So what's the best way to replace the GenericPrincipal?

Thanks in advance,

Pickels

like image 239
Pickels Avatar asked May 04 '10 17:05

Pickels


1 Answers

You are missing a subtle detail, the thread.

    Context.User = Thread.CurrentPrincipal = new CustomPrincipal....

Will get you where you need to go.

Also I notice you mention that you need to only replace the principal. If this is the case, you can simply reuse the FormsIdentity that has already been constructed for you as shown below.

    Context.User = Thread.CurrentPrincipal = new CustomPrincipal(Context.User.Identity /*, add roles here if desired*/ );
like image 166
Sky Sanders Avatar answered Sep 27 '22 17:09

Sky Sanders