xsockets.net

Using PrincipalPermissions attribute in XSockets.Net 4.0


Inside XSockets controller I need to call Api (Assembly) that has PrincipalPermissions attribute on its methods for specific roles, and is not aware of host it is running in (can be also called in batch process, WebApi controller, etc...) I understand that XScockets store identity/principal in its own ConnectionContext object and its custom Authorize attribute which is used by controller OnAuthorization method.

The question is whether it is possible to use existing code with principal permissions, so it always gets correct roles from caller context.

I thought of two options:

1) Switch thread principal in my authentication pipeline, so ConnectionContext and current thread have same principal:

    var identity = new GenericIdentity(authenticationTicket.Name);
    string[] roles = authenticationTicket.UserData.Split('|');
    var principal = new GenericPrincipal(identity, roles);
    protocol.ConnectionContext.User = principal;
    **Thread.CurrentPrincipal = principal;**

2) Do it in OnAuthorization override in controller:

    public override bool OnAuthorization(IAuthorizeAttribute authorizeAttribute)
    {
        Thread.CurrentPrincipal = ConnectionContext.User;
        return base.OnAuthorization(authorizeAttribute);
    }

The second approach seems to work in my basic tests. Actually when I do it this way, it is enough to mark controller class with [Authorize] attribute once and then I am able to use PrincipalPermission and even some of my custom CodeAccessSecurity attributes on controller methods.

Is it safe to do so? Is there some asynchronous behavior that will make it error prone? What are the alternatives?


Solution

  • Currently solution 2 I described seems to work fine. Since nobody attempted to reply I will accept it as an answer and continue testing.