How to set custom principal in asp.net

D J picture D J · Feb 25, 2013 · Viewed 9.5k times · Source

I am new to web application. I have created a custom principle and trying to set it in CurrentDomain. This code works perfectly in WPF application. But here it is throwing Policy Exception "Default principal object cannot be set twice."

 var principal = new CustomPrinciple(currentIdentity);
 Thread.CurrentPrincipal = principal;
 AppDomain.CurrentDomain.SetThreadPrincipal(Thread.CurrentPrincipal);

My CustomPrincple is derived from ClaimsPrinciple

  public class CustomPrinciple : ClaimsPrincipal
  { }

I am wondering why I am not allowed to set it here. How can I set my custom principle in web application.

Answer

marvc1 picture marvc1 · Feb 25, 2013

The custom principal should be set the in global.asax file for the request made, not the thread. Then you get hold of the custom principal from HttpContext.User Property

This answer in this question details the best way to do it: ASP.NET MVC - Set custom IIdentity or IPrincipal