I am trying to allow and disallow access to a method in a controller. For this I added the AuthorizationFilter class, the problem I have is that I cannot pass a value to that class from the method before it is executed.
public class AuthorizationFilter : Attribute, IAuthorizationFilter
{
public AuthorizationFilter()
{
}
void IAuthorizationFilter.OnAuthorization(AuthorizationFilterContext context)
{
try
{
if (context.HttpContext.Request.Headers.ContainsKey("Authorization"))
{
string token = context.HttpContext.Request.Headers["Authorization"];
if (!string.IsNullOrEmpty(token) && token.Contains("Bearer"))
{
//validate IdRol with value into System.Security.Claims.ClaimsPrincipal
}
else
context.Result = new UnauthorizedResult();
}
else
context.Result = new UnauthorizedResult();
}
catch (Exception exc)
{
Debug.WriteLine(exc);
context.Result = new UnauthorizedResult();
}
}
}
The class that should receive a value of type System.Security.Claims.ClaimsPrincipal is AuthorizationFilter. In it I must receive the claims to identify whether or not the user has access to the method.
[Produces("application/json")]
[Route("api/[controller]")]
[ApiController]
public class ClientesController : ControllerBase
{
[TypeFilter(typeof(AuthorizationFilter))]//The claims inside this.User are what I must pass to the AuthorizationFilter class before execute the method
[HttpGet(Name = nameof(GetClients))]
public async Task<IActionResult> GetClients([FromQuery] ClientsSearch filter)
{
//The claims inside this.User are what I must pass to the AuthorizationFilter class before execute the method
//System.Security.Claims.ClaimsPrincipal user = this.User;
return Ok();
}
}
Please can you help me solve the problem I have, thank you very much.