S
S
Saharman2018-10-18 00:49:29
ASP.NET
Saharman, 2018-10-18 00:49:29

How to get a role that starts with certain characters?

I want to check if the current user belongs to a role starting with certain letters (for example, for admin with the letters "ad"). Is there such a possibility at all? If yes, how can this be done?
PS the fact that you can get a list of user roles and check them for these criteria, I already know

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
eRKa, 2018-10-18
@Saharman

If it's Core, then use policies, something like

public void ConfigureServices(IServiceCollection services)
{
  services.AddAuthorization(x => 
  {
    x.AddPolicy("RoleStartWith", policy => { 
        policy.RequireRole(roles.Where(r => r.StartsWith("ad")));
      });
  });
}

[Authorize(Policy = "RoleStartWith")]
public IActionResult Index()
{
  return View();
}

If this is, for example, MVC5, then you can use a custom attribute like this:
public class CustomAutorizeAttribute : AuthorizeAttribute
{
  private string _prefix;
  private string[] _roles;

  public CustomAutorizeAttribute(string prefix)
  {
    _prefix = prefix;
    _roles = base.Roles.Split(',').Select(x => x.Trim()).ToArray();
  }

  protected override bool AuthorizeCore(HttpContextBase httpContext)
  {
    return _roles.Where(x => x.StartsWith(_prefix)).Any(x => httpContext.User.IsInRole(x));
  }
}

[CustomAutorize(prefix = "ad")]
public IActionResult Index()
{
  return View();
}

I wrote everything on my knee in a notebook, I didn’t check it with my hands, but the main idea, I hope, is clear.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question