Asp.net:替换GenericPrincipal

Pic*_*els 6 asp.net security asp.net-mvc asp.net-membership

我想知道用我自己的CustomGenericPrincipal替换genericPrincipal最好的方法是什么.

目前我有这样的事情,但我不确定它是否正确.

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

我需要替换它,因为我需要一个实现我的ICustomPrincipal接口的Principal,因为我正在使用Ninject执行以下操作:

Bind<ICustomPrincipal>().ToMethod(x => (ICustomPrincipal)HttpContext.Current.User)
                        .InRequestScope();
Run Code Online (Sandbox Code Playgroud)

那么替换GenericPrincipal的最佳方法是什么?

提前致谢,

Pickels

Sky*_*ers 5

你错过了一个微妙的细节,线程.

    Context.User = Thread.CurrentPrincipal = new CustomPrincipal....
Run Code Online (Sandbox Code Playgroud)

将带你到你需要去的地方.

另外我注意到你提到你只需要替换校长.如果是这种情况,您可以简单地重用已经为您构造的FormsIdentity,如下所示.

    Context.User = Thread.CurrentPrincipal = new CustomPrincipal(Context.User.Identity /*, add roles here if desired*/ );
Run Code Online (Sandbox Code Playgroud)