3

I created an ASP.NET Web API 2 end point, with controllers protected with the [Authorized] attribute.

Unauthenticated access will get 401 UnAuthorized http status.

Now, I want to log those unauthorized access to a log file. However, I don't know where to handle the unauthorized access.

1 Answer 1

4

The solution would just be to create a custom Authorize filter inheriting from default Authorize attribute this way:

public class LogAuthorizeAttribute : AuthorizeAttribute
{
    protected override bool IsAuthorized(System.Web.Http.Controllers.HttpActionContext actionContext)
    {
        var authorized = base.IsAuthorized(actionContext);
        if (!authorized)
        {
            // log the denied access attempt.
        }
        return authorized;
    }
}

This way, you keep the same authorize validation from parent, but you can do additional thing such as logging in your case for unauthorized access.

You can then simply use it on your Web API methods:

public class ValuesController : ApiController
{
    [LogAuthorize]
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

really? Isn't there a global access point, filter or ish where you can intercept this and log without having to replace all your Authorize attribute?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.