too much abstractions with efcore and ms-identity as I am learning the framework adn c# from roots for this persoal project.
so i defined custom attributes
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
public class PermAttribute(params string[] allowedRoles) : Attribute, IActionFilter
{
private readonly string[] _allowedRoles = allowedRoles ?? throw new ArgumentNullException(nameof(allowedRoles));
public void OnActionExecuted(ActionExecutedContext context) { }
public void OnActionExecuting(ActionExecutingContext context)
{
IPermissionService permissionService = context.HttpContext.RequestServices.GetService<IPermissionService>() ?? throw new InvalidOperationException("Service error");
string currentRole = permissionService.CurrentRole();
bool isAuthorized = Array.Exists(_allowedRoles, role => role == currentRole);
//if (!isAuthorized) context.Result = new RedirectToActionResult("AccessDenied", "Error", null);
if (!isAuthorized)
{
// Assuming "AccessDenied" is the name of your view
ViewResult viewResult = new()
{
ViewName = "~/Views/Home/AccessDenied.cshtml"
};
context.Result = viewResult;
}
}
}
and used it in controllers like the authorize thingy but as action filters
[Perm("user", "admin", "editor")]
[HttpPost("/api/account/clearallsessions")]
public async Task<IActionResult> DisposeSessionKey()
{
if (await _authRepo.DisposeSessionKey(HttpContext.Session.GetString("username"))) return Ok();
else return BadRequest("unable to dispose session key");
}
if i understand correctly. you use that method to check that user has access to that url or not. yes what you are doing is right.
Обсуждают сегодня