Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread.CurrentPrincipal.Identity in ASP .NET - is it safe to use

Inside my AuthenticateRequest event handler I set Thread's principal. Here'a a part of my IHttpModule:

    public void Init(HttpApplication context)
    {
        context.AuthenticateRequest += AuthenticateRequest;
    }

    private void AuthenticateRequest(object sender, EventArgs e)
    {
        var principal = CreatePrincipal();
        HttpContext.Current.User = principal;
    }

But I have an assembly, that should not have access to System.Web, so I cannot use HttpContext.Current.User, but I need to access current principal. My very first thought was to change my method to:

System.Threading.Thread.CurrentPrincipal = HttpContext.Current.User = principal;

and use Thread.CurrentPrincipal when needed.

But as far as I remember it is not safe to store request specific stuff in Thread Local Storage as multiple threads can handle the same request, so I guess it is the same with Thread.CurrentPrincipal. Or not?

like image 428
dragonfly Avatar asked Oct 30 '13 13:10

dragonfly


1 Answers

I disagree with Jeff Moser's answer.

The standard .NET authorization stuff all works using Thread.CurrentPrincipal. e.g.:

PrincipalPermissionAttribute
PrincipalPermission.Demand

Also, if you configure a .NET RoleProvider, it will set Thread.CurrentPrincipal to the same principal as HttpContext.User.

Therefore this is the standard way to do it, and I would do the same thing in your custom authentication code (or even better - implement it as a custom RoleProvider).

As for asynchronous I/O, this blog post states that Thread.CurrentPrincipal and culture settings are automatically passed to the new thread.

Using Thread.CurrentPrincipal is arguably more secure, if your library is using the principal for authorization purposes, because untrusted code can pass in a principal as an argument, while CAS might prevent it from setting Thread.CurrentPrincipal.

like image 61
Joe Avatar answered Nov 19 '22 11:11

Joe