سؤال

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?

هل كانت مفيدة؟

المحلول

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top