Answer the question
In order to leave comments, you need to log in
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
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();
}
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();
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question