0

I'm working inside of ConfigureServices of my Startup class. I want to run IsInRole() which I understand to be this method in order to populate an Action:

However, running:

System.Security.Principal.IPrincipal.IsInRole("BRV_Projects_Edit");

Is clearly not successful as this refers to an interface, not an instance implementing that interface?

My Question is, within the context of ConfigureService, where I am defining a custom attribute how can I access (inject?) the Principal of the current user.

ekad
  • 14,436
  • 26
  • 44
  • 46
ffejrekaburb
  • 656
  • 1
  • 10
  • 35
  • no you can't because startup code runs before it starts listening for web requests and there isn't any httpcontext yet – Joe Audette Jan 31 '19 at 15:53
  • 1
    HttpContext.User aka claimsprincipal of the current user does not exist until after the authentication middleware runs. – Joe Audette Jan 31 '19 at 16:00
  • any way to get HttpContext into an ActionFilterAttribute? – ffejrekaburb Jan 31 '19 at 16:02
  • this may answer it https://stackoverflow.com/questions/16649551/get-user-name-on-action-filter – ffejrekaburb Jan 31 '19 at 16:03
  • 1
    Possible duplicate of [Get User Name on Action Filter](https://stackoverflow.com/questions/16649551/get-user-name-on-action-filter) – Chris Pratt Jan 31 '19 at 16:09
  • 1
    Thanks looking at it now, looks like there are some differences MVC4 vs .net core – ffejrekaburb Jan 31 '19 at 16:10
  • It is all different in aspnet core. Take a look at: https://learn.microsoft.com/en-us/aspnet/core/security/authorization/roles?view=aspnetcore-2.2 Seems like `[Authorize(Role="xxx")]` would be what you need – mortb Jan 31 '19 at 16:14

1 Answers1

0

Per the feedback above User.InRole is not accessible at this point in the pipeline but is accessible via the creation of an ActionFilterAttribute.

The ActionFilterAttribute makes available OnActionExecuting, Get User Name on Action Filter extremely similar to this post except with changes relevant to .net core

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (filterContext.Controller is Controller controller)
        {
            controller.ViewBag.CanEdit = filterContext.HttpContext.User.IsInRole("group1");
ffejrekaburb
  • 656
  • 1
  • 10
  • 35