title: .NET Core MVC add role claim to local user when in development before authorization
body: <p>I'm looking for an "easy" way to automatically add role claims to the local user in order to test my authorization logic; that is, wanting to add some specific claims to the local user before they are authorized by my controllers. </p>
  
  <p>I've learned that in the past something akin to this could be done for the controllers:</p>
  
  <pre><code>#if DEBUG 
  protected override void OnAuthorization(AuthorizationContext filterContext)
  {
      var roles = new[] { "role-under-test"};
      HttpContext.User = new GenericPrincipal(new GenericIdentity("DebugUser"), roles);
      base.OnAuthorization(filterContext);
  }
  #endif
  </code></pre>
  
  <p>Yet that was prior to .NET Core which is what I'm working in now. Slowly I've worked my way to the code presented below,  which seems to work, but is clearly much more of a hassle compared to the above example. So my question is whether anyone knows a better--more easy--way to achieve this?</p>
  
  <p>The custom authorization attribute:</p>
  
  <pre><code>public class CustomAuthAttribute : RolesAuthorizationRequirement {
      public CustomAuthAttribute(IEnumerable&lt;string&gt; allowedRoles) : base(allowedRoles) { }
  
      protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, RolesAuthorizationRequirement requirement) {
  #if DEBUG
          context.User.AddIdentity(new ClaimsIdentity(new GenericIdentity("DebugUser"), new[] {
              new Claim(ClaimsIdentity.DefaultRoleClaimType, "users"),
              new Claim(ClaimsIdentity.DefaultRoleClaimType, "admins")
          }));
  #endif
          return base.HandleRequirementAsync(context, requirement);
      }
  }
  </code></pre>
  
  <p>In Startup.cs</p>
  
  <pre><code>public void ConfigureServices(IServiceCollection services) {
      // ...
  
      services.AddAuthorization( options =&gt;
          options.AddPolicy("UsersAndAdmins",
              policy =&gt; policy.AddRequirements(new CustomAuthAttribute(new []{"users", "admins"}))));
  }
  </code></pre>
  
  <p>And then using it in the controllers:</p>
  
  <pre><code>[Authorize(Policy = "UsersAndAdmins")]    
  public class HomeController : Controller {
      // ...
  </code></pre>