Hi!
I have a simple web api controller that i want to secure with claims authorization:
[ClaimsPrincipalPermission(SecurityAction.Demand, Operation = "Get", Resource = "Contacts")] public IHttpActionResult Get() { return Ok("Some contacts.."); }
I am not sure how to handle security exceptions with attributes filter, i've tried something like this:
public class SecurityExeceptionFilterAttribute : ExceptionFilterAttribute { public override void OnException(HttpActionExecutedContext actionExecutedContext) { if (actionExecutedContext.Exception is SecurityException) { actionExecutedContext.Response.StatusCode = System.Net.HttpStatusCode.Unauthorized; actionExecutedContext.Response.Headers.Add("EXCEPTION", "_SECURITY"); } }
[SecurityExceptionFilter]
[ClaimsPrincipalPermission(SecurityAction.Demand, Operation = "Get", Resource = "Contacts")] public IHttpActionResult Get() { return Ok("Some contacts.."); }
But this does not work, the filter is not called when a SecurityException is thrown.
The only way i found to got this to work is to not use the attributes:
public IHttpActionResult Get() { try { ClaimsPrincipalPermission.CheckAccess("Get", "Contacts"); return Ok("Some contacts.."); } catch (Exception e) { var responseMsg = new HttpResponseMessage(HttpStatusCode.Unauthorized); responseMsg.Headers.Add("EXCEPTION", "_SECURITY"); IHttpActionResult response = ResponseMessage(responseMsg); return response; } }
This works, but i prefer to use attributes. Which is the correct way to implement this exception handling with attributes?
thanks in advance!